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) {
  try {
    const session = await getServerSession(authOptions);
    if (!session?.user?.email)
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const userEmail = session.user.email;
    const { searchParams } = new URL(req.url);
    const videoId = searchParams.get('videoId');

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

    const user = await prisma.user.findUnique({ where: { email: userEmail } });
    if (!user)
      return NextResponse.json({ error: 'user not found' }, { status: 404 });

    // Validate that the video exists
    const video = await prisma.video.findUnique({ where: { id: videoId } });
    if (!video) {
      console.debug(`[PROGRESS] Video not found for segments: ${videoId} (likely deleted video with cached browser reference)`);
      return NextResponse.json({ error: 'video not found' }, { status: 404 });
    }

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

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