import { useState, createContext, useContext } from 'react'
import axios from 'axios'

const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:3001/api'

export const AuthContext = createContext(null)

export function useAuth() {
  return useContext(AuthContext)
}

async function login(username, password) {
  const response = await axios.post(`${API_URL}/auth/login`, { username, password })
  localStorage.setItem('token', response.data.token)
  localStorage.setItem('user', JSON.stringify(response.data.user))
  return response.data
}

async function logout() {
  localStorage.removeItem('token')
  localStorage.removeItem('user')
}

async function register(username, password) {
  const response = await axios.post(`${API_URL}/auth/register`, { username, password })
  return response.data
}

async function fetchAllCrawls() {
  const token = localStorage.getItem('token')
  const response = await axios.get(`${API_URL}/crawler/all`, {
    headers: { Authorization: `Bearer ${token}` }
  })
  return response.data
}

async function fetchCrawlById(id) {
  const token = localStorage.getItem('token')
  const response = await axios.get(`${API_URL}/crawler/${id}`, {
    headers: { Authorization: `Bearer ${token}` }
  })
  return response.data
}

async function runAllCrawls() {
  const token = localStorage.getItem('token')
  const response = await axios.post(`${API_URL}/crawler/run-all`, {}, {
    headers: { Authorization: `Bearer ${token}` }
  })
  return response.data
}

async function fetchCasinoReport() {
  const token = localStorage.getItem('token')
  const response = await axios.get(`${API_URL}/crawler/casino-report`, {
    headers: { Authorization: `Bearer ${token}` }
  })
  return response.data
}

async function getPositionHistory(casinoName, siteName) {
  const token = localStorage.getItem('token')
  const response = await axios.get(`${API_URL}/crawler/position-history`, {
    headers: { Authorization: `Bearer ${token}` },
    params: { casino_name: casinoName, site_name: siteName }
  })
  return response.data
}

export default { login, logout, register, fetchAllCrawls, fetchCrawlById, runAllCrawls, fetchCasinoReport, getPositionHistory }
