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

// POST - Bulk toggle favorites (add if not exists, remove if exists)
export async function POST(request: NextRequest) {
  try {
    const session = await auth();
    if (!session?.user?.id) {
      return NextResponse.json(
        { error: 'Authentication required. Please sign in to favorite photos.' },
        { status: 401 }
      );
    }

    const { photoIds, action } = await request.json();
    const userId = parseInt(session.user.id, 10);

    if (isNaN(userId)) {
      return NextResponse.json(
        { error: 'Invalid user ID' },
        { status: 400 }
      );
    }

    if (!Array.isArray(photoIds) || photoIds.length === 0) {
      return NextResponse.json(
        { error: 'Photo IDs array is required' },
        { status: 400 }
      );
    }

    // Validate action
    if (action && action !== 'add' && action !== 'remove' && action !== 'toggle') {
      return NextResponse.json(
        { error: 'Action must be "add", "remove", or "toggle"' },
        { status: 400 }
      );
    }

    const validPhotoIds = photoIds
      .map((id: any) => parseInt(id, 10))
      .filter((id: number) => !isNaN(id));

    if (validPhotoIds.length === 0) {
      return NextResponse.json(
        { error: 'No valid photo IDs provided' },
        { status: 400 }
      );
    }

    // Verify user exists in auth database
    const user = await prismaAuth.user.findUnique({
      where: { id: userId },
      select: { id: true },
    });

    if (!user) {
      return NextResponse.json(
        { error: 'User account not found. Please sign in again.' },
        { status: 404 }
      );
    }

    // Verify photos exist in main database
    const existingPhotos = await prisma.photo.findMany({
      where: { id: { in: validPhotoIds } },
      select: { id: true },
    });

    const existingPhotoIds = new Set(existingPhotos.map(p => p.id));
    const validIds = validPhotoIds.filter((id: number) => existingPhotoIds.has(id));

    if (validIds.length === 0) {
      return NextResponse.json(
        { error: 'No valid photos found' },
        { status: 404 }
      );
    }

    // Get current favorites for these photos
    const currentFavorites = await prismaAuth.photoFavorite.findMany({
      where: {
        userId,
        photoId: { in: validIds },
      },
      select: {
        photoId: true,
        id: true,
      },
    });

    const favoritedPhotoIds = new Set(currentFavorites.map(f => f.photoId));
    const favoriteIdsToDelete = new Set(currentFavorites.map(f => f.id));

    let added = 0;
    let removed = 0;

    if (action === 'add') {
      // Only add favorites that don't exist
      const toAdd = validIds.filter(id => !favoritedPhotoIds.has(id));
      
      if (toAdd.length > 0) {
        await prismaAuth.photoFavorite.createMany({
          data: toAdd.map(photoId => ({
            photoId,
            userId,
            favoritedAt: new Date(),
          })),
          skipDuplicates: true,
        });
        added = toAdd.length;
      }
    } else if (action === 'remove') {
      // Only remove favorites that exist
      if (favoriteIdsToDelete.size > 0) {
        await prismaAuth.photoFavorite.deleteMany({
          where: {
            id: { in: Array.from(favoriteIdsToDelete) },
          },
        });
        removed = favoriteIdsToDelete.size;
      }
    } else {
      // Toggle: add if not favorited, remove if favorited
      const toAdd = validIds.filter(id => !favoritedPhotoIds.has(id));
      const toRemove = Array.from(favoriteIdsToDelete);

      if (toAdd.length > 0) {
        await prismaAuth.photoFavorite.createMany({
          data: toAdd.map(photoId => ({
            photoId,
            userId,
            favoritedAt: new Date(),
          })),
          skipDuplicates: true,
        });
        added = toAdd.length;
      }

      if (toRemove.length > 0) {
        await prismaAuth.photoFavorite.deleteMany({
          where: {
            id: { in: toRemove },
          },
        });
        removed = toRemove.length;
      }
    }

    return NextResponse.json({
      success: true,
      added,
      removed,
      total: validIds.length,
      message: `Favorites updated: ${added} added, ${removed} removed`,
    });
  } catch (error: any) {
    console.error('Error bulk toggling favorites:', error);
    
    // Handle case where table doesn't exist yet (P2021 = table does not exist)
    if (error.code === 'P2021') {
      return NextResponse.json(
        { error: 'Favorites feature is not available yet. Please run the migration: migrations/add-photo-favorites-table.sql' },
        { status: 503 }
      );
    }
    
    return NextResponse.json(
      { error: 'Failed to update favorites', details: error.message },
      { status: 500 }
    );
  }
}






