import { useState, useCallback, type ReactNode } from 'react';
import { AuthContext } from './AuthContext';
import { sha512 } from '../utils/crypto';
import type { AuthResponse } from '../types/auth';

// Pobieramy bazowy adres i usuwamy ewentualny ukośnik na końcu
// Używamy import.meta.env, który jest dostępny wewnątrz kodu React
const API_BASE_URL = (import.meta.env.VITE_API_TARGET || '').replace(/\/$/, '');

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) => {
       

        if (!API_BASE_URL) {
            const msg = "Błąd konfiguracji: VITE_API_TARGET jest pusty. Sprawdź plik .env i restartuj serwer.";
            setError(msg);
            return null;
        }

        setLoading(true);
        setError(null);
        try {
            const hashedPassword = await sha512(pass);
            const fullUrl = `${API_BASE_URL}/api/v1/user/${endpoint}`;

            

            const response = await fetch(fullUrl, {
                method: 'POST',
                headers: {
                    'accept': 'application/json',
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ name, password: hashedPassword, ttl: 86400 }),
            });

            const contentType = response.headers.get("content-type");
            let data: AuthResponse | null = null;

            if (contentType && contentType.includes("application/json")) {
                data = await response.json();
            }

            if (!response.ok) {
                const errorMsg = data?.error || data?.message || `Błąd serwera: ${response.status}`;
                throw new Error(errorMsg);
            }

            if (data && data.token) {
                sessionStorage.setItem('ktty_token', data.token);
                setToken(data.token);
            }
            return data;
        } catch (err: unknown) {
            const message = err instanceof Error ? err.message : 'Unknown error';
            setError(message);
            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>
    );
}