import {FastifyReply, FastifyRequest} from 'fastify';
import * as listService from './list.service';

interface UserRequest extends FastifyRequest {
    user?: { id: number };
}

interface EntryParams {
    entryId: string;

}

interface SingleEntryQuery {
    source: string;
    entry_type: string;
}

export async function getList(req: UserRequest, reply: FastifyReply) {
    const userId = req.user?.id;
    if (!userId) {
        return reply.code(401).send({ error: "Unauthorized" });
    }

    try {
        const results = await listService.getUserList(userId);
        return { results };
    } catch (err) {
        console.error(err);
        return reply.code(500).send({ error: "Failed to retrieve list" });
    }
}

export async function getSingleEntry(req: UserRequest, reply: FastifyReply) {
    const userId = req.user?.id;
    const { entryId } = req.params as EntryParams;
    const { source, entry_type } = req.query as SingleEntryQuery;

    if (!userId) {
        return reply.code(401).send({ error: "Unauthorized" });
    }

    if (!entryId || !source || !entry_type) {
        return reply.code(400).send({ error: "Missing required identifier: entryId, source, or entry_type." });
    }

    try {

        const entry = await listService.getSingleListEntry(
            userId,
            entryId,
            source,
            entry_type
        );

        if (!entry) {

            return reply.code(404).send({ found: false, message: "Entry not found in user list." });
        }

        return { found: true, entry: entry };
    } catch (err) {
        console.error(err);
        return reply.code(500).send({ error: "Failed to retrieve list entry" });
    }
}

export async function upsertEntry(req: UserRequest, reply: FastifyReply) {
    const userId = req.user?.id;
    const body = req.body as any;

    if (!userId) {
        return reply.code(401).send({ error: "Unauthorized" });
    }

    if (!body.entry_id || !body.source || !body.status || !body.entry_type) {
        return reply.code(400).send({
            error: "Missing required fields (entry_id, source, status, entry_type)."
        });
    }

    try {
        const entryData = {
            user_id: userId,
            entry_id: body.entry_id,
            external_id: body.external_id,
            source: body.source,
            entry_type: body.entry_type,
            status: body.status,
            progress: body.progress || 0,
            score: body.score || null,
            start_date: body.start_date || null,
            end_date: body.end_date || null,
            repeat_count: body.repeat_count ?? 0,
            notes: body.notes || null,
            is_private: body.is_private ?? 0
        };

        const result = await listService.upsertListEntry(entryData);

        return { success: true, changes: result.changes };
    } catch (err) {
        console.error(err);
        return reply.code(500).send({ error: "Failed to save list entry" });
    }
}

export async function deleteEntry(req: UserRequest, reply: FastifyReply) {
    const userId = req.user?.id;
    const { entryId } = req.params as EntryParams;
    const { source } = req.query as { source?: string }; // ✅ VIENE DEL FRONT

    if (!userId) {
        return reply.code(401).send({ error: "Unauthorized" });
    }

    if (!entryId || !source) {
        return reply.code(400).send({ error: "Missing entryId or source." });
    }

    try {
        const result = await listService.deleteListEntry(
            userId,
            entryId,
            source
        );

        if (result.success) {
            return { success: true, external: result.external };
        } else {
            return reply.code(404).send({
                error: "Entry not found or unauthorized to delete."
            });
        }
    } catch (err) {
        console.error(err);
        return reply.code(500).send({ error: "Failed to delete list entry" });
    }
}

export async function getListByFilter(req: UserRequest, reply: FastifyReply) {
    const userId = req.user?.id;
    const { status, entry_type } = req.query as any;

    if (!userId) {
        return reply.code(401).send({ error: "Unauthorized" });
    }

    if (!status && !entry_type) {
        return reply.code(400).send({
            error: "At least one filter is required (status or entry_type)."
        });
    }

    try {
        const results = await listService.getUserListByFilter(
            userId,
            status,
            entry_type
        );

        return { results };
    } catch (err) {
        console.error(err);
        return reply.code(500).send({ error: "Failed to retrieve filtered list" });
    }
}