// app/api/likes/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 body = await req.json().catch(() => ({}));
    const { videoId, isLiked } = body ?? {};

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

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

    if (isLiked) {
      // Add like
      const existingLike = await prisma.videoLike.findUnique({
        where: { userId_videoId: { userId: user.id, videoId } },
      });

      if (existingLike) {
        return NextResponse.json({ success: true, message: 'Already liked' });
      }

      await prisma.videoLike.create({
        data: {
          userId: user.id,
          videoId,
        },
      });

      return NextResponse.json({ success: true, message: 'Video liked' });
    } else {
      // Remove like
      await prisma.videoLike.deleteMany({
        where: { userId: user.id, videoId },
      });

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

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

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

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

    if (videoId) {
      // Check if a specific video is liked
      const like = await prisma.videoLike.findUnique({
        where: { userId_videoId: { userId: user.id, videoId } },
      });
      return NextResponse.json({ isLiked: !!like });
    } else {
      // Get all liked videos for user
      return NextResponse.json({ error: 'videoId required for check' }, { status: 400 });
    }
  } catch (err: any) {
    console.error('like check error', err);
    return NextResponse.json(
      { error: err?.message ?? 'server error' },
      { status: 500 }
    );
  }
}
