import { NextResponse } from 'next/server';
import { PrismaClient } from '@prisma/client';
import { requireAdminAuth } from '@/lib/auth';

const prisma = new PrismaClient();

export async function GET() {
    try {
        const today = new Date().toISOString().split('T')[0];

        const dailyPuzzles = await prisma.dailyPuzzle.findMany({
            where: {
                date: today
            },
            include: {
                song: true,
                genre: true,
                special: true
            },
            orderBy: [
                { genreId: 'asc' },
                { specialId: 'asc' }
            ]
        });

        const formattedPuzzles = dailyPuzzles.map(puzzle => ({
            id: puzzle.id,
            date: puzzle.date,
            category: puzzle.specialId
                ? `★ ${puzzle.special?.name}`
                : puzzle.genreId
                    ? `🏷️ ${puzzle.genre?.name}`
                    : '🌍 Global',
            categoryType: puzzle.specialId ? 'special' : puzzle.genreId ? 'genre' : 'global',
            genreId: puzzle.genreId,
            specialId: puzzle.specialId,
            song: {
                id: puzzle.song.id,
                title: puzzle.song.title,
                artist: puzzle.song.artist,
                filename: puzzle.song.filename,
                audioUrl: `/api/audio/${puzzle.song.filename}`
            }
        }));

        // Filter out duplicates (keep only the first one per category)
        // This matches the behavior of getOrCreateDailyPuzzle which uses findFirst
        const uniquePuzzles = [];
        const seenCategories = new Set();

        for (const puzzle of formattedPuzzles) {
            const key = `${puzzle.categoryType}-${puzzle.genreId || 'null'}-${puzzle.specialId || 'null'}`;
            if (!seenCategories.has(key)) {
                seenCategories.add(key);
                uniquePuzzles.push(puzzle);
            }
        }

        return NextResponse.json(uniquePuzzles);
    } catch (error) {
        console.error('Error fetching daily puzzles:', error);
        return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
    }
}

export async function DELETE(request: Request) {
    // Check authentication
    const authError = await requireAdminAuth(request as any);
    if (authError) return authError;

    try {
        const { puzzleId } = await request.json();

        if (!puzzleId) {
            return NextResponse.json({ error: 'Missing puzzleId' }, { status: 400 });
        }

        // Get puzzle details before deletion
        const puzzle = await prisma.dailyPuzzle.findUnique({
            where: { id: Number(puzzleId) }
        });

        if (!puzzle) {
            return NextResponse.json({ error: 'Puzzle not found' }, { status: 404 });
        }

        // Delete the puzzle
        await prisma.dailyPuzzle.delete({
            where: { id: Number(puzzleId) }
        });

        // Regenerate puzzle based on type
        const { getOrCreateDailyPuzzle, getOrCreateSpecialPuzzle } = await import('@/lib/dailyPuzzle');

        let newPuzzle;
        if (puzzle.specialId) {
            const special = await prisma.special.findUnique({
                where: { id: puzzle.specialId }
            });
            if (special) {
                newPuzzle = await getOrCreateSpecialPuzzle(special);
            }
        } else if (puzzle.genreId) {
            const genre = await prisma.genre.findUnique({
                where: { id: puzzle.genreId }
            });
            if (genre) {
                newPuzzle = await getOrCreateDailyPuzzle(genre);
            }
        } else {
            newPuzzle = await getOrCreateDailyPuzzle(null);
        }

        return NextResponse.json({
            success: true,
            message: 'Puzzle deleted and regenerated',
            newPuzzle
        });
    } catch (error) {
        console.error('Error deleting puzzle:', error);
        return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
    }
}
