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

const prisma = new PrismaClient();

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

        const genres = await prisma.genre.findMany({
            // orderBy: { name: 'asc' }, // Cannot sort by JSON field easily in SQLite
            include: {
                _count: {
                    select: { songs: true }
                }
            }
        });

        // Sort in memory if needed, or just return
        // If locale is provided, map to localized values
        if (locale) {
            const localizedGenres = genres.map(g => ({
                ...g,
                name: getLocalizedValue(g.name, locale),
                subtitle: getLocalizedValue(g.subtitle, locale)
            })).sort((a, b) => a.name.localeCompare(b.name));
            return NextResponse.json(localizedGenres);
        }

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

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

    try {
        const { name, subtitle, active } = await request.json();

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

        // Ensure name is stored as JSON
        const nameData = typeof name === 'string' ? { de: name, en: name } : name;
        const subtitleData = subtitle ? (typeof subtitle === 'string' ? { de: subtitle, en: subtitle } : subtitle) : null;

        const genre = await prisma.genre.create({
            data: {
                name: nameData,
                subtitle: subtitleData,
                active: active !== undefined ? active : true
            },
        });

        return NextResponse.json(genre);
    } catch (error) {
        console.error('Error creating genre:', 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 { id } = await request.json();

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

        await prisma.genre.delete({
            where: { id: Number(id) },
        });

        return NextResponse.json({ success: true });
    } catch (error) {
        console.error('Error deleting genre:', error);
        return NextResponse.json({ error: 'Internal Server Error' }, { status: 500 });
    }
}

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

    try {
        const { id, name, subtitle, active } = await request.json();

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

        const updateData: any = {};
        if (name) updateData.name = typeof name === 'string' ? { de: name, en: name } : name;
        if (subtitle !== undefined) updateData.subtitle = subtitle ? (typeof subtitle === 'string' ? { de: subtitle, en: subtitle } : subtitle) : null;
        if (active !== undefined) updateData.active = active;

        const genre = await prisma.genre.update({
            where: { id: Number(id) },
            data: updateData,
        });

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