import { FastifyReply, FastifyRequest } from 'fastify';
import { getExtension, getExtensionsList, getGalleryExtensionsMap, getBookExtensionsMap, getAnimeExtensionsMap, saveExtensionFile, deleteExtensionFile } from '../../shared/extensions';
import { ExtensionNameRequest } from '../types';

export async function getExtensions(req: FastifyRequest, reply: FastifyReply) {
    return { extensions: getExtensionsList() };
}

export async function getAnimeExtensions(req: FastifyRequest, reply: FastifyReply) {
    const animeExtensions = getAnimeExtensionsMap();
    return { extensions: Array.from(animeExtensions.keys()) };
}

export async function getBookExtensions(req: FastifyRequest, reply: FastifyReply) {
    const bookExtensions = getBookExtensionsMap();
    return { extensions: Array.from(bookExtensions.keys()) };
}

export async function getGalleryExtensions(req: FastifyRequest, reply: FastifyReply) {
    const galleryExtensions = getGalleryExtensionsMap();
    return { extensions: Array.from(galleryExtensions.keys()) };
}

export async function getExtensionSettings(req: ExtensionNameRequest, reply: FastifyReply) {
    const { name } = req.params;
    const ext = getExtension(name);

    if (!ext) {
        return { error: "Extension not found" };
    }

    if (!ext.getSettings) {
        return { episodeServers: ["default"], supportsDub: false };
    }

    return ext.getSettings();
}

export async function installExtension(req: any, reply: FastifyReply) {
    const { fileName } = req.body;

    if (!fileName || !fileName.endsWith('.js')) {
        return reply.code(400).send({ error: "Invalid extension fileName provided" });
    }

    try {

        const downloadUrl = `https://git.waifuboard.app/ItsSkaiya/WaifuBoard-Extensions/raw/branch/main/${fileName}`

        await saveExtensionFile(fileName, downloadUrl);

        req.server.log.info(`Extension installed: ${fileName}`);
        return reply.code(200).send({ success: true, message: `Extension ${fileName} installed successfully.` });

    } catch (error) {
        req.server.log.error(`Failed to install extension ${fileName}:`, error);
        return reply.code(500).send({ success: false, error: `Failed to install extension ${fileName}.` });
    }
}

export async function uninstallExtension(req: any, reply: FastifyReply) {
    const { fileName } = req.body;

    if (!fileName || !fileName.endsWith('.js')) {
        return reply.code(400).send({ error: "Invalid extension fileName provided" });
    }

    try {

        await deleteExtensionFile(fileName);

        req.server.log.info(`Extension uninstalled: ${fileName}`);
        return reply.code(200).send({ success: true, message: `Extension ${fileName} uninstalled successfully.` });

    } catch (error) {

        // @ts-ignore
        if (error.code === 'ENOENT') {
            return reply.code(200).send({ success: true, message: `Extension ${fileName} already uninstalled (file not found).` });
        }

        req.server.log.error(`Failed to uninstall extension ${fileName}:`, error);
        return reply.code(500).send({ success: false, error: `Failed to uninstall extension ${fileName}.` });
    }
}