// src/context/AuthProvider.tsx
import { useState, useCallback, type ReactNode } from 'react';
import { AuthContext } from './AuthContext'; // Importujemy stałą z pliku obok
import { sha512 } from '../utils/crypto';
import type { AuthResponse } from '../types/auth';

export function AuthProvider({ children }: { children: ReactNode }) {
    const [token, setToken] = useState<string | null>(sessionStorage.getItem('ktty_token'));
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);

    const authRequest = useCallback(async (endpoint: 'signUp' | 'signIn', name: string, pass: string) => {
        setLoading(true);
        setError(null);
        try {
            const hashedPassword = await sha512(pass);
            const response = await fetch(`/api/v1/user/${endpoint}`, {
                method: 'POST',
                headers: {
                    'accept': 'application/json',
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ name, password: hashedPassword, ttl: 86400 }),
            });

            const data: AuthResponse = await response.json();
            if (!response.ok) throw new Error(data.error || data.message || `Error ${response.status}`);

            if (data.token) {
                sessionStorage.setItem('ktty_token', data.token);
                setToken(data.token); // To aktualizuje stan w całej aplikacji natychmiast!
            }
            return data;
        } catch (err: unknown) {
            setError(err instanceof Error ? err.message : 'Unknown error');
            return null;
        } finally {
            setLoading(false);
        }
    }, []);

    const logout = useCallback(() => {
        sessionStorage.removeItem('ktty_token');
        setToken(null);
    }, []);

    return (
        <AuthContext.Provider value={{
            isAuthenticated: !!token,
            token,
            loading,
            error,
            signIn: (n, p) => authRequest('signIn', n, p),
            signUp: (n, p) => authRequest('signUp', n, p),
            logout
        }}>
            {children}
        </AuthContext.Provider>
    );
}