import {FastifyReply, FastifyRequest} from 'fastify';
import * as booksService from './books.service';
import {getExtension} from '../../shared/extensions';
import {BookRequest, ChapterRequest, SearchRequest} from '../types';

export async function getBook(req: any, reply: FastifyReply) {
    try {
        const { id } = req.params;
        const source = req.query.source;

        let book;
        if (source === 'anilist') {
            book = await booksService.getBookById(id);
        } else {
            const ext = getExtension(source);
            const result = await booksService.getBookInfoExtension(ext, id);
            book = result || null;
        }

        return book;
    } catch (err) {
        return { error: (err as Error).message };
    }
}


export async function getTrending(req: FastifyRequest, reply: FastifyReply) {
    try {
        const results = await booksService.getTrendingBooks();
        return { results };
    } catch (err) {
        return { results: [] };
    }
}

export async function getPopular(req: FastifyRequest, reply: FastifyReply) {
    try {
        const results = await booksService.getPopularBooks();
        return { results };
    } catch (err) {
        return { results: [] };
    }
}

export async function searchBooks(req: SearchRequest, reply: FastifyReply) {
    try {
        const query = req.query.q;

        const dbResults = await booksService.searchBooksLocal(query);
        if (dbResults.length > 0) {
            return { results: dbResults };
        }

        console.log(`[Books] Local DB miss for "${query}", fetching live...`);
        const anilistResults = await booksService.searchBooksAniList(query);
        if (anilistResults.length > 0) {
            return { results: anilistResults };
        }

        return { results: [] };

    } catch (e) {
        const error = e as Error;
        console.error("Search Error:", error.message);
        return { results: [] };
    }
}

export async function searchBooksInExtension(req: any, reply: FastifyReply) {
    try {
        const extensionName = req.params.extension;
        const query = req.query.q;

        const ext = getExtension(extensionName);
        if (!ext) return { results: [] };

        const results = await booksService.searchBooksInExtension(ext, extensionName, query);
        return { results };
    } catch (e) {
        const error = e as Error;
        console.error("Search Error:", error.message);
        return { results: [] };
    }
}

export async function getChapters(req: any, reply: FastifyReply) {
    try {
        const { id } = req.params;
        const source = req.query.source || 'anilist';
        const provider = req.query.provider;

        const isExternal = source !== 'anilist';
        return await booksService.getChaptersForBook(id, isExternal, provider);
    } catch (err) {
        console.error(err);
        return { chapters: [] };
    }
}

export async function getChapterContent(req: any, reply: FastifyReply) {
    try {
        const { bookId, chapter, provider } = req.params;
        const source = req.query.source || 'anilist';

        const content = await booksService.getChapterContent(
            bookId,
            chapter,
            provider,
            source
        );

        return reply.send(content);
    } catch (err) {
        console.error("getChapterContent error:", (err as Error).message);
        return reply.code(500).send({ error: "Error loading chapter" });
    }
}
