import { ISource, SearchResult, SelectionData, ContentLinks, MediaType } from '../../src/types/source.js';
import { FlixArtAPI } from './api.js';

export class FlixartSource implements ISource {
    name = 'flixart';
    displayName = 'FlixArt';

    async search(query: string, mediaType?: MediaType): Promise<SearchResult[]> {
        return FlixArtAPI.search(query, mediaType);
    }

    async getTrending(mediaType: MediaType): Promise<SearchResult[]> {
        const type = mediaType === 'series' ? 'series' : 'movie';
        return FlixArtAPI.getTrending(type);
    }

    async getRecent(): Promise<SearchResult[]> {
        return this.getTrending('movie');
    }

    async getSelection(identifier: string, type?: string, seasonValue?: string | number): Promise<SelectionData> {
        return FlixArtAPI.getSelection(identifier);
    }

    async getContentLinks(identifier: string, season?: number): Promise<ContentLinks> {
        return FlixArtAPI.getContentLinks(identifier, season);
    }

    async healthCheck(): Promise<boolean> {
        try {
            const results = await this.getTrending('movie');
            return results.length > 0;
        } catch (e) {
            console.error('[FlixArt] Healthcheck failed:', e);
            return false;
        }
    }

    // Custom resolveLink that returns a Turnstile challenge instead of just the URL
    // Actually, Agora's activeSource.resolveLink only accepts string.
    // We will change ISource resolveLink to allow returning an object.
    async resolveLink(linkId: string, extraData?: any): Promise<any> {
        const [url] = linkId.split('|');
        // FlixArt requires a Cloudflare Turnstile challenge which cannot be resolved on localhost.
        // We directly return the manual redirection challenge.
        return {
            captcha: 'turnstile',
            url: url
        };
    }
}

// Auto-registration
import { sourceRegistry } from '../../src/core/registry.js';
sourceRegistry.register(new FlixartSource());
