// app/api/admin/reorder-videos/route.ts
import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth-options';
import { prisma } from '@/lib/prisma';

export async function POST(req: Request) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.email)
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const role = (session as any)?.user?.role ?? null;
    if (!(role === 'admin' || role === 'superadmin')) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
    }

    const body = await req.json().catch(() => ({}));
    const { playlistId, orderedIds } = body ?? {};
    if (!playlistId || !Array.isArray(orderedIds))
      return NextResponse.json({ error: 'playlistId and orderedIds required' }, { status: 400 });

    // Validate that all video ids belong to the playlist (optional)
    const vids = await prisma.video.findMany({ where: { playlistId }, select: { id: true } });
    const validIds = new Set(vids.map((v) => v.id));
    const invalid = orderedIds.find((id: string) => !validIds.has(id));
    if (invalid)
      return NextResponse.json({ error: 'Invalid video id in orderedIds' }, { status: 400 });

    // Use two-phase update to avoid unique constraint violation:
    // Phase 1: Set all indices to negative temporary values
    // Phase 2: Set to final positive values
    await prisma.$transaction([
      // Phase 1: Set temporary negative indices to avoid conflicts
      ...orderedIds.map((id: string, idx: number) =>
        prisma.video.update({
          where: { id },
          data: { index: -(idx + 1) }, // Use negative values: -1, -2, -3, etc.
        })
      ),
      // Phase 2: Set to final indices
      ...orderedIds.map((id: string, idx: number) =>
        prisma.video.update({
          where: { id },
          data: { index: idx },
        })
      ),
    ]);

    return NextResponse.json({ success: true });
  } catch (err: any) {
    console.error('reorder videos error', err);
    return NextResponse.json({ error: err?.message ?? 'server error' }, { status: 500 });
  }
}
