import { createContext, useContext, useState, useEffect } from "react"
import api from "../api/axios"

const AuthContext = createContext(null)

export function AuthProvider({ children }) {
  const [user, setUser] = useState(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    const token = sessionStorage.getItem("access_token")
    if (!token) {
      setLoading(false)
      return
    }
    api.get("/me")
      .then(({ data }) => setUser(data))
      .catch(() => {
        sessionStorage.clear()
        setUser(null)
      })
      .finally(() => setLoading(false))
  }, [])

  async function login(username, password) {
    const form = new URLSearchParams()
    form.append("username", username)
    form.append("password", password)
    
    const { data } = await api.post("/auth/login", form, {
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
    })
    
    sessionStorage.setItem("access_token", data.access_token)
    sessionStorage.setItem("refresh_token", data.refresh_token)
    
    const me = await api.get("/me")
    setUser(me.data)
  }

  async function register(username, email, password) {
    // Registration returns user data, and emails the verification OTP code
    await api.post("/auth/register", { username, email, password })
  }

  // ─── SMTP ROUTING FUNCTIONS ───

  async function verifyEmail(email, code) {
    await api.post("/auth/verify-email", { email, code })
  }

  async function forgotPassword(email) {
    await api.post("/auth/forgot-password", { email })
  }

  async function resetPassword(email, code, new_password) {
    await api.post("/auth/reset-password", { email, code, new_password })
  }

  async function logout() {
    const refreshToken = sessionStorage.getItem("refresh_token")
    try {
      await api.post("/auth/logout", { refresh_token: refreshToken })
    } catch (err) {
      console.warn("Logout request to server failed, clearing local session.", err)
    } finally {
      sessionStorage.clear()
      setUser(null)
    }
  }

  async function updateProfile(profileData) {
    const { data } = await api.put("/me", profileData)
    setUser(data)
    return data;
  }

  async function deleteAccount() {
    await api.delete("/me")
    sessionStorage.clear()
    setUser(null)
  }

  return (
    <AuthContext.Provider value={{ 
      user, 
      loading, 
      login, 
      register, 
      logout, 
      updateProfile, 
      deleteAccount, 
      verifyEmail,
      forgotPassword,
      resetPassword 
    }}>
      {children}
    </AuthContext.Provider>
  )
}

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