import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth-options';
import { prisma } from '@/lib/prisma';

export async function GET(
  req: Request,
  { params }: { params: Promise<{ userId: string; videoId: string }> }
) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.email)
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    // Check if user is admin
    const admin = await prisma.user.findUnique({ where: { email: session.user.email } });
    if (!admin || (admin.role !== 'admin' && admin.role !== 'superadmin'))
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 });

    const { userId, videoId } = await params;

    // Fetch all watch segments for the specified user+video
    const segments = await prisma.videoWatchSegment.findMany({
      where: { userId, videoId },
      select: { startSec: true, endSec: true, watchedAt: true },
      orderBy: { createdAt: 'asc' },
    });

    return NextResponse.json({ segments });
  } catch (err: any) {
    console.error('admin segments GET error', err);
    return NextResponse.json(
      { error: err?.message ?? 'server error' },
      { status: 500 }
    );
  }
}
