'use client';

import { createContext, useContext, useEffect, useState, useCallback } from 'react';
import { checkAuthServer } from '@/lib/api/auth';

// 인증 상태 Context
const AuthContext = createContext<{
	isLoading: boolean;
	isAuthenticated: boolean;
	setIsAuthenticated: (value: boolean) => void;
	checkAuth: () => Promise<boolean>;
}>({
	isLoading: true,
    isAuthenticated: false,
    setIsAuthenticated: () => {},
	checkAuth: async () => false
});

// Context Provider
export function AuthProvider({ children }: { children: React.ReactNode }) {
    const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
    const [isLoading, setIsLoading] = useState<boolean>(true);

	const checkAuth = useCallback(async (): Promise<boolean> => {
	    try {
			const ret = await checkAuthServer();
			setIsAuthenticated(ret);
			setIsLoading(false);
			return ret;
		} catch {
			console.error("인증 확인 중 오류 발생");
			setIsAuthenticated(false);
			return false;
		}
	}, []);

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

	// 401 Auth:unauthroized 이벤트 수신
	useEffect(() => {
		const eventKey = 'auth:unauthorized';
		const handleUnauthorized = () => {
			setIsAuthenticated(false);
			localStorage.setItem('rememberMe', 'false');
			localStorage.removeItem('member');

			if (!window.location.pathname.startsWith('/login')) {
				window.location.replace(`/login?returnUrl=${encodeURIComponent(window.location.pathname + window.location.search)}`);
			}
		};

		window.addEventListener(eventKey, handleUnauthorized);
		return () => window.removeEventListener(eventKey, handleUnauthorized);
	}, []);

    return (
        <AuthContext.Provider value={{ isLoading, isAuthenticated, setIsAuthenticated, checkAuth }}>
            {children}
        </AuthContext.Provider>
    );
}

// Context 사용을 위한 커스텀 훅
export function useAuthContext() {
    return useContext(AuthContext);
}