import {FastifyReply, FastifyRequest} from 'fastify';
import * as galleryService from './gallery.service';

export async function searchInExtension(req: any, reply: FastifyReply) {
    try {
        const provider = req.query.provider;
        const query = req.query.q || '';
        const page = parseInt(req.query.page as string) || 1;
        const perPage = parseInt(req.query.perPage as string) || 48;

        if (!provider) {
            return reply.code(400).send({ error: "Missing provider" });
        }

        return await galleryService.searchInExtension(provider, query, page, perPage);

    } catch (err) {
        console.error("Gallery SearchInExtension Error:", (err as Error).message);

        return {
            results: [],
            total: 0,
            page: 1,
            hasNextPage: false
        };
    }
}

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

        return await galleryService.getGalleryInfo(id, provider);
    } catch (err) {
        const error = err as Error;
        console.error("Gallery Info Error:", error.message);
        return reply.code(404).send({ error: "Gallery item not found" });
    }
}

export async function getFavorites(req: any, reply: FastifyReply) {
    try {
        if (!req.user) return reply.code(401).send({ error: "Unauthorized" });

        const favorites = await galleryService.getFavorites(req.user.id);
        return { favorites };
    } catch (err) {
        console.error("Get Favorites Error:", (err as Error).message);
        return reply.code(500).send({ error: "Failed to retrieve favorites" });
    }
}

export async function getFavoriteById(req: any, reply: FastifyReply) {
    try {
        if (!req.user) return reply.code(401).send({ error: "Unauthorized" });

        const { id } = req.params as { id: string };

        const favorite = await galleryService.getFavoriteById(id, req.user.id);

        if (!favorite) {
            return reply.code(404).send({ error: "Favorite not found" });
        }

        return { favorite };

    } catch (err) {
        console.error("Get Favorite By ID Error:", (err as Error).message);
        return reply.code(500).send({ error: "Failed to retrieve favorite" });
    }
}

export async function addFavorite(req: any, reply: FastifyReply) {
    try {
        if (!req.user) return reply.code(401).send({ error: "Unauthorized" });

        const { id, title, image_url, thumbnail_url, tags, provider, headers } = req.body;

        if (!id || !title || !image_url || !thumbnail_url) {
            return reply.code(400).send({
                error: "Missing required fields"
            });
        }

        const result = await galleryService.addFavorite({
            id,
            user_id: req.user.id,
            title,
            image_url,
            thumbnail_url,
            tags: tags || '',
            provider: provider || "",
            headers: headers || ""
        });

        if (result.success) {
            return reply.code(201).send(result);
        } else {
            return reply.code(409).send(result);
        }

    } catch (err) {
        console.error("Add Favorite Error:", (err as Error).message);
        return reply.code(500).send({ error: "Failed to add favorite" });
    }
}

export async function removeFavorite(req: any, reply: FastifyReply) {
    try {
        if (!req.user) return reply.code(401).send({ error: "Unauthorized" });

        const { id } = req.params;

        const result = await galleryService.removeFavorite(id, req.user.id);

        if (result.success) {
            return { success: true, message: "Favorite removed successfully" };
        } else {
            return reply.code(404).send({ error: "Favorite not found" });
        }
    } catch (err) {
        console.error("Remove Favorite Error:", (err as Error).message);
        return reply.code(500).send({ error: "Failed to remove favorite" });
    }
}