import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { requireApiAuth } from '@/lib/api-auth';

export async function PUT(request: Request) {
    const authError = await requireApiAuth();
    if (authError) return authError;

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

        if (!Array.isArray(updates)) {
            return NextResponse.json({ error: 'Invalid updates' }, { status: 400 });
        }
        if (updates.length === 0) {
            return NextResponse.json({ success: true });
        }
        const isValid = updates.every(
            (update) =>
                update &&
                typeof update === 'object' &&
                typeof update.id === 'string' &&
                update.id.length > 0 &&
                Number.isInteger(update.order)
        );
        if (!isValid) {
            return NextResponse.json({ error: 'Invalid updates payload' }, { status: 400 });
        }
        const ids = updates.map((update: { id: string }) => update.id);
        if (new Set(ids).size !== ids.length) {
            return NextResponse.json({ error: 'Duplicate page ids in updates' }, { status: 400 });
        }

        // Transaction for batch update
        await prisma.$transaction(
            updates.map((update: { id: string, order: number }) =>
                prisma.page.update({
                    where: { id: update.id },
                    data: { order: update.order },
                })
            )
        );

        return NextResponse.json({ success: true });
    } catch {
        return NextResponse.json({ error: 'Error reordering pages' }, { status: 500 });
    }
}
