// app/api/user/unlocks/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 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 user = await prisma.user.findUnique({
      where: { email: userEmail },
      select: { id: true },
    });
    
    if (!user)
      return NextResponse.json({ error: 'user not found' }, { status: 404 });

    // Fetch all VideoUnlock records for this user
    const unlocks = await prisma.videoUnlock.findMany({
      where: { userId: user.id },
      select: { id: true, videoId: true, unlockedAt: true, createdAt: true },
      orderBy: { unlockedAt: 'desc' },
    });

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

export async function POST(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 body = await req.json();
    const { videoId } = body;

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

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

    // Verify video exists
    const video = await prisma.video.findUnique({
      where: { id: videoId },
      select: { id: true, locked: true, instantAccess: true },
    });

    if (!video) {
      return NextResponse.json({ error: 'video not found' }, { status: 404 });
    }

    // Check if already unlocked
    const existingUnlock = await prisma.videoUnlock.findUnique({
      where: { userId_videoId: { userId: user.id, videoId } },
    });

    if (existingUnlock) {
      return NextResponse.json({ 
        message: 'Video already unlocked',
        unlock: existingUnlock 
      });
    }

    // Create the unlock record
    const unlock = await prisma.videoUnlock.create({
      data: {
        userId: user.id,
        videoId: videoId,
      },
    });

    return NextResponse.json({ 
      message: 'Video unlocked successfully',
      unlock 
    });

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