import { CONFIG } from '../../src/utils/config.js';

export class FS24Auth {
    private static sessionCookie: string | null = null;
    private static lastLoginTime: number = 0;

    public static async getCookie(forceRefresh = false): Promise<string> {
        // If we already have a cookie and it's less than 12 hours old, return it
        if (!forceRefresh && this.sessionCookie && Date.now() - this.lastLoginTime < 12 * 60 * 60 * 1000) {
            return this.sessionCookie;
        }

        const username = CONFIG.FS24_USERNAME;
        const password = CONFIG.FS24_PASSWORD;
        const baseUrl = CONFIG.FS24_URL;

        if (!username || !password) {
            throw new Error('[FS24 Auth] Identifiants manquants.');
        }

        console.log(`[FS24] Tentative de connexion avec l'utilisateur: ${username}...`);

        try {
            const params = new URLSearchParams();
            params.append('login_name', username);
            params.append('login_password', password);
            params.append('login', 'submit');

            const response = await fetch(baseUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                    'Referer': baseUrl
                },
                body: params.toString(),
                redirect: 'manual' // Capture the set-cookie from the redirect
            });

            // Collect cookies from the response headers
            const setCookieHeader = response.headers.get('set-cookie');
            if (setCookieHeader) {
                // Parse DLE / PHP session cookies
                const cookies = setCookieHeader.split(',').map(c => c.split(';')[0].trim());
                this.sessionCookie = cookies.join('; ');
                this.lastLoginTime = Date.now();
                console.log(`[FS24] ✅ Connexion réussie ! (Cookie généré)`);
                return this.sessionCookie;
            } else {
                console.warn(`[FS24] ⚠️ Pas de header set-cookie retourné. Les identifiants sont-ils valides ?`);
                throw new Error('Échec de la connexion (Pas de cookie de session).');
            }
        } catch (error: any) {
            console.error('[FS24] ❌ Erreur lors de la connexion:', error.message);
            throw error;
        }
    }
}
