import { FastifyInstance } from "fastify";
import { run } from "../../shared/database";

async function anilist(fastify: FastifyInstance) {
    fastify.post("/anilist/store", async (request, reply) => {
        try {
            const {
                userId,
                accessToken,
                tokenType = "Bearer",
                expiresIn
            } = request.body as {
                userId: number;
                accessToken: string;
                tokenType?: string;
                expiresIn?: number;
            };

            if (!userId || !accessToken) {
                return reply.status(400).send({ error: "Faltan datos (User ID o Token)" });
            }

            // 1. Verificar que el token es válido consultando a AniList
            const userRes = await fetch("https://graphql.anilist.co", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    Authorization: `${tokenType} ${accessToken}`
                },
                body: JSON.stringify({
                    query: `query { Viewer { id } }`
                })
            });

            if (!userRes.ok) {
                return reply.status(401).send({ error: "Token de AniList inválido o expirado" });
            }

            const userData = await userRes.json();
            const anilistUserId = userData?.data?.Viewer?.id;

            if (!anilistUserId) {
                return reply.status(500).send({ error: "No se pudo obtener el ID de usuario de AniList" });
            }

            const expiresAt = new Date(
                Date.now() + 365 * 24 * 60 * 60 * 1000
            ).toISOString();

            await run(
                `
                    INSERT INTO UserIntegration
                    (user_id, platform, access_token, refresh_token, token_type, anilist_user_id, expires_at)
                    VALUES (?, ?, ?, ?, ?, ?, ?)
                        ON CONFLICT(user_id) DO UPDATE SET
                        access_token = excluded.access_token,
                                                    refresh_token = excluded.refresh_token,
                                                    token_type = excluded.token_type,
                                                    anilist_user_id = excluded.anilist_user_id,
                                                    expires_at = excluded.expires_at
                `,
                [
                    userId,
                    "AniList",
                    accessToken,
                    "",          // <- aquí
                    tokenType,
                    anilistUserId,
                    expiresAt
                ],
                "userdata"
            );

            return reply.send({ ok: true, anilistUserId });
        } catch (e) {
            console.error("AniList error:", e);
            return reply.status(500).send({ error: "Error interno del servidor al guardar AniList" });
        }
    });
}

export default anilist;