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

export class MovixAPI {
    private static get baseUrl(): string {
        return CONFIG.MOVIX_URL || '';
    }
    
    private static get apiUrl(): string {
        if (!this.baseUrl) return '';
        try {
            const url = new URL(this.baseUrl);
            return `${url.protocol}//api.${url.host}/api`;
        } catch {
            return '';
        }
    }

    private static getHeaders() {
        return {
            'Accept': 'application/json, text/plain, */*',
            'Origin': this.baseUrl,
            'Referer': `${this.baseUrl}/`,
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36 OPR/133.0.0.0'
        };
    }

    public static async search(query: string): Promise<any> {
        const url = `${this.apiUrl}/search?title=${encodeURIComponent(query)}`;
        const res = await fetch(url, { headers: this.getHeaders() });
        if (!res.ok) throw new Error(`Movix Search HTTP ${res.status}`);
        return res.json();
    }

    public static async getDownloadLinks(type: string, id: number | string, tmdbId: number | string): Promise<any> {
        const url = `${this.apiUrl}/darkiworld/download/${type}/${id}?tmdbId=${tmdbId}`;
        const res = await fetch(url, { headers: this.getHeaders() });
        if (!res.ok) throw new Error(`Movix Download HTTP ${res.status}`);
        return res.json();
    }

    public static async decodeLink(linkId: string | number, titleId: string | number): Promise<any> {
        const url = `${this.apiUrl}/darkiworld/decode/${linkId}?title_id=${titleId}`;
        const res = await fetch(url, { headers: this.getHeaders() });
        if (!res.ok) throw new Error(`Movix Decode HTTP ${res.status}`);
        return res.json();
    }
}
