import { NextRequest, NextResponse } from 'next/server';
import { prismaAuth } from '@/lib/db';
import { auth } from '@/app/api/auth/[...nextauth]/route';

export async function POST(request: NextRequest) {
  try {
    const session = await auth();
    if (!session?.user?.id) {
      return NextResponse.json({ results: {} });
    }

    const userId = parseInt(session.user.id, 10);
    if (isNaN(userId)) {
      return NextResponse.json({ results: {} });
    }

    const { photoIds } = await request.json();
    
    if (!Array.isArray(photoIds) || photoIds.length === 0) {
      return NextResponse.json({ results: {} });
    }

    // Fetch all favorites for this user and these photos
    const favorites = await prismaAuth.photoFavorite.findMany({
      where: {
        userId,
        photoId: { in: photoIds },
      },
      select: {
        photoId: true,
      },
    });

    // Build result map
    const favoriteSet = new Set(favorites.map(f => f.photoId));
    const results: Record<string, boolean> = {};
    
    photoIds.forEach((photoId: number) => {
      results[photoId.toString()] = favoriteSet.has(photoId);
    });

    return NextResponse.json({ results });
  } catch (error: any) {
    // Handle case where table doesn't exist yet (P2021 = table does not exist)
    if (error.code === 'P2021') {
      console.warn('photo_favorites table does not exist yet. Run migration: migrations/add-photo-favorites-table.sql');
      return NextResponse.json({ results: {} });
    }
    console.error('Error fetching batch favorites:', error);
    return NextResponse.json({ results: {} });
  }
}

