import { NextResponse } from 'next/server';
import { getOrCreateDailyPuzzle } from '@/lib/dailyPuzzle';
import { PrismaClient } from '@prisma/client';
import { getLocalizedValue } from '@/lib/i18n';

const prisma = new PrismaClient();

export async function GET(request: Request) {
    try {
        const { searchParams } = new URL(request.url);
        const genreName = searchParams.get('genre');

        let genre = null;
        if (genreName) {
            // Find genre by localized name (try both locales)
            const allGenres = await prisma.genre.findMany();
            genre = allGenres.find(g =>
                getLocalizedValue(g.name, 'de') === genreName ||
                getLocalizedValue(g.name, 'en') === genreName
            ) || null;
        }

        const puzzle = await getOrCreateDailyPuzzle(genre);

        if (!puzzle) {
            return NextResponse.json({ error: 'Failed to get or create puzzle' }, { status: 404 });
        }

        return NextResponse.json(puzzle);

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