import { useState, useCallback, type ReactNode } from 'react';
import Cookies from 'js-cookie'; // Importujemy bibliotekę do ciasteczek
import { AuthContext } from './AuthContext';
import { sha512 } from '../utils/crypto';
import type { AuthResponse } from '../types/auth';

const TOKEN_KEY = 'ktty_shared_token';
const PARENT_DOMAIN = '.ktty.is'; // Kropka na początku pozwala na dostęp ze wszystkich subdomen

const getSubdomain = (): string | null => {
    const hostname = window.location.hostname;
    const parts = hostname.split('.');
    if (parts.length <= 2) return null;
    return parts[0];
};

export function AuthProvider({ children }: { children: ReactNode }) {
    const subdomain = getSubdomain();

    // Pobieramy token z ciasteczka zamiast z sessionStorage
    const [token, setToken] = useState<string | null>(Cookies.get(TOKEN_KEY) || null);
    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 fullUrl = `/api/v1/user/${endpoint}`;

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

            const data: AuthResponse = await response.json();

            if (!response.ok) {
                throw new Error(data?.error || data?.message || 'Błąd logowania');
            }

            if (data?.token) {
                // ZAPISYWANIE CIASTECZKA DLA WSZYSTKICH SUBDOMEN
                Cookies.set(TOKEN_KEY, data.token, {
                    domain: PARENT_DOMAIN,
                    expires: 1, // 1 dzień
                    secure: true, // Wymagane dla HTTPS
                    sameSite: 'lax'
                });
                setToken(data.token);
            }
            return data;
        } catch (err: unknown) {
            let errorMessage = 'Wystąpił nieoczekiwany błąd';
            if (err instanceof Error) errorMessage = err.message;
            setError(errorMessage);
            return null;
        } finally {
            setLoading(false);
        }
    }, [subdomain]);

    const logout = useCallback(() => {
        // Usuwamy ciasteczko z domeny nadrzędnej
        Cookies.remove(TOKEN_KEY, { domain: PARENT_DOMAIN });
        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>
    );
}