"use client";

import { createContext, useContext, useEffect, useState } from "react";
import { refreshSession, User, getCurrentUser } from "@/lib/auth";

interface AuthContextType {
    user: User | null;
    loading: boolean;
    checkSession: () => Promise<void>;
}

const AuthContext = createContext<AuthContextType>({
    user: null,
    loading: true,
    checkSession: async () => { },
});

export function AuthProvider({ children }: { children: React.ReactNode }) {
    const [user, setUser] = useState<User | null>(null);
    const [loading, setLoading] = useState(true);

    const checkSession = async () => {
        try {
            // First check local storage for immediate feedback (optimistic)
            const stored = getCurrentUser();
            if (stored) {
                setUser(stored);
            }

            // Then verify with backend (httpOnly cookie)
            const refreshedUser = await refreshSession();
            if (refreshedUser) {
                setUser(refreshedUser);
            } else {
                // If backend fails but we had local storage, it means session invalid/expired
                // refreshSession already clears localStorage in that case
                setUser(null);
            }
        } catch (error) {
            console.error("Auth initialization failed", error);
            setUser(null);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        checkSession();
    }, []);

    return (
        <AuthContext.Provider value={{ user, loading, checkSession }}>
            {children}
        </AuthContext.Provider>
    );
}

export const useAuth = () => useContext(AuthContext);
