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

export class FS24API {
    private static get baseUrl(): string {
        return CONFIG.FS24_URL;
    }

    /**
     * Recherche AJAX via /engine/ajax/search.php
     */
    public static async fetchSearch(query: string, page: number = 1): Promise<string> {
        const cookie = await FS24Auth.getCookie();
        const searchUrl = `${this.baseUrl}/engine/ajax/search.php`;

        const params = new URLSearchParams();
        params.append('query', query);
        params.append('page', page.toString());

        console.log(`[FS24] Recherche: "${query}" (page ${page})`);

        const response = await fetch(searchUrl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
                'Cookie': cookie,
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: params.toString()
        });

        if (!response.ok) {
            throw new Error(`HTTP Error ${response.status}`);
        }

        return await response.text();
    }

    /**
     * Récupère la page HTML d'un contenu pour extraire le news_id
     */
    public static async fetchPage(pathOrUrl: string): Promise<string> {
        const cookie = await FS24Auth.getCookie();
        const url = pathOrUrl.startsWith('http') ? pathOrUrl : `${this.baseUrl}${pathOrUrl.startsWith('/') ? '' : '/'}${pathOrUrl}`;

        const response = await fetch(url, {
            method: 'GET',
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
                'Cookie': cookie
            }
        });

        if (!response.ok) {
            throw new Error(`HTTP Error ${response.status}`);
        }

        return await response.text();
    }

    /**
     * Récupère la page des tendances (films ou séries)
     */
    public static async fetchTrending(mediaType: 'movie' | 'series'): Promise<string> {
        const cookie = await FS24Auth.getCookie();
        const url = mediaType === 'series' ? `${this.baseUrl}/s-tv/` : `${this.baseUrl}/films/`;

        console.log(`[FS24] Chargement des tendances ${mediaType}`);

        const response = await fetch(url, {
            method: 'GET',
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
                'Cookie': cookie
            }
        });

        if (!response.ok) throw new Error(`HTTP Error ${response.status}`);
        return await response.text();
    }

    /**
     * Récupère la page des ajouts récents
     */
    public static async fetchRecent(): Promise<string> {
        const cookie = await FS24Auth.getCookie();
        const url = `${this.baseUrl}/film-commu/`;

        console.log(`[FS24] Chargement des ajouts récents`);

        const response = await fetch(url, {
            method: 'GET',
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
                'Cookie': cookie
            }
        });

        if (!response.ok) throw new Error(`HTTP Error ${response.status}`);
        return await response.text();
    }

    /**
     * Appelle l'API JSON /engine/ajax/release-api.php pour récupérer les releases communautaires.
     * C'est ici que se trouvent les vrais liens de téléchargement (fsprotect encodés en base64).
     */
    public static async fetchReleases(newsId: string): Promise<any> {
        const cookie = await FS24Auth.getCookie();
        const url = `${this.baseUrl}/engine/ajax/release-api.php?action=release_list&post_id=${newsId}`;

        console.log(`[FS24] Chargement des releases pour post_id=${newsId}`);

        const response = await fetch(url, {
            method: 'GET',
            headers: {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
                'Cookie': cookie,
                'X-Requested-With': 'XMLHttpRequest'
            }
        });

        if (!response.ok) {
            throw new Error(`HTTP Error ${response.status}`);
        }

        return await response.json();
    }
}
