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

const prisma = new PrismaClient();

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

    const specials = await prisma.special.findMany({
        // orderBy: { name: 'asc' },
        include: {
            _count: {
                select: { songs: true }
            }
        }
    });

    if (locale) {
        const localizedSpecials = specials.map(s => ({
            ...s,
            name: getLocalizedValue(s.name, locale),
            subtitle: getLocalizedValue(s.subtitle, locale)
        })).sort((a, b) => a.name.localeCompare(b.name));
        return NextResponse.json(localizedSpecials);
    }

    return NextResponse.json(specials);
}

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

    const { name, subtitle, maxAttempts = 7, unlockSteps = '[2,4,7,11,16,30,60]', launchDate, endDate, curator, hidden = false } = await request.json();
    if (!name) {
        return NextResponse.json({ error: 'Name is required' }, { status: 400 });
    }

    // Validate unlockSteps JSON
    if (unlockSteps) {
        try {
            const parsed = JSON.parse(unlockSteps);
            if (!Array.isArray(parsed)) {
                return NextResponse.json({ error: 'Unlock steps must be a JSON array' }, { status: 400 });
            }
            if (parsed.some((item: any) => typeof item !== 'number' || item < 1)) {
                return NextResponse.json({ error: 'All unlock step values must be positive numbers' }, { status: 400 });
            }
        } catch (e) {
            return NextResponse.json({ error: 'Invalid JSON format for unlock steps. Please use an array of numbers, e.g. [2,4,7,11,16,30,60]' }, { 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 special = await prisma.special.create({
        data: {
            name: nameData,
            subtitle: subtitleData,
            maxAttempts: Number(maxAttempts),
            unlockSteps,
            launchDate: launchDate ? new Date(launchDate) : null,
            endDate: endDate ? new Date(endDate) : null,
            curator: curator || null,
            hidden: Boolean(hidden),
        },
    });
    return NextResponse.json(special);
}

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

    const { id } = await request.json();
    if (!id) {
        return NextResponse.json({ error: 'ID required' }, { status: 400 });
    }
    await prisma.special.delete({ where: { id: Number(id) } });
    return NextResponse.json({ success: true });
}

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

    const { id, name, subtitle, maxAttempts, unlockSteps, launchDate, endDate, curator, hidden } = await request.json();
    if (!id) {
        return NextResponse.json({ error: 'ID required' }, { status: 400 });
    }

    // Validate unlockSteps JSON if provided
    if (unlockSteps !== undefined) {
        try {
            const parsed = JSON.parse(unlockSteps);
            if (!Array.isArray(parsed)) {
                return NextResponse.json({ error: 'Unlock steps must be a JSON array' }, { status: 400 });
            }
            if (parsed.some((item: any) => typeof item !== 'number' || item < 1)) {
                return NextResponse.json({ error: 'All unlock step values must be positive numbers' }, { status: 400 });
            }
        } catch (e) {
            return NextResponse.json({ error: 'Invalid JSON format for unlock steps. Please use an array of numbers, e.g. [2,4,7,11,16,30,60]' }, { 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 (maxAttempts) updateData.maxAttempts = Number(maxAttempts);
    if (unlockSteps) updateData.unlockSteps = unlockSteps;
    if (launchDate !== undefined) updateData.launchDate = launchDate ? new Date(launchDate) : null;
    if (endDate !== undefined) updateData.endDate = endDate ? new Date(endDate) : null;
    if (curator !== undefined) updateData.curator = curator || null;
    if (hidden !== undefined) updateData.hidden = Boolean(hidden);

    const updated = await prisma.special.update({
        where: { id: Number(id) },
        data: updateData,
    });
    return NextResponse.json(updated);
}
