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

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

    const { id } = await params;
    const photoId = parseInt(id, 10);
    const userId = parseInt(session.user.id, 10);

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

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

    // Verify photo exists in main database
    const photo = await prisma.photo.findUnique({
      where: { id: photoId },
      select: { id: true, filename: true },
    });

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

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

    if (!user) {
      console.error(`[FAVORITE] User ${userId} not found in auth database`);
      return NextResponse.json(
        { error: 'User account not found. Please sign in again.' },
        { status: 404 }
      );
    }

    // Check if favorite already exists
    const existing = await prismaAuth.photoFavorite.findUnique({
      where: {
        uq_photo_user_favorite: {
          photoId,
          userId,
        },
      },
    });

    if (existing) {
      // Remove favorite
      await prismaAuth.photoFavorite.delete({
        where: { id: existing.id },
      });
      return NextResponse.json({ 
        favorited: false,
        message: 'Photo removed from favorites' 
      });
    } else {
      // Add favorite
      await prismaAuth.photoFavorite.create({
        data: {
          photoId,
          userId,
          favoritedAt: new Date(),
        },
      });
      return NextResponse.json({ 
        favorited: true,
        message: 'Photo added to favorites' 
      });
    }
  } catch (error: any) {
    console.error('Error toggling favorite:', 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 }
      );
    }
    
    if (error.code === 'P2002') {
      return NextResponse.json(
        { error: 'Favorite already exists' },
        { status: 409 }
      );
    }
    
    return NextResponse.json(
      { error: 'Failed to toggle favorite', details: error.message },
      { status: 500 }
    );
  }
}

// GET - Check if photo is favorited
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await auth();
    if (!session?.user?.id) {
      return NextResponse.json({ favorited: false });
    }

    const { id } = await params;
    const photoId = parseInt(id, 10);
    const userId = parseInt(session.user.id, 10);

    if (isNaN(photoId) || isNaN(userId)) {
      return NextResponse.json({ favorited: false });
    }

    const favorite = await prismaAuth.photoFavorite.findUnique({
      where: {
        uq_photo_user_favorite: {
          photoId,
          userId,
        },
      },
    });

    return NextResponse.json({ favorited: !!favorite });
  } catch (error: any) {
    // Handle case where table doesn't exist yet (P2021 = table does not exist)
    if (error.code === 'P2021') {
      // Table doesn't exist yet, return false (not favorited)
      return NextResponse.json({ favorited: false });
    }
    console.error('Error checking favorite:', error);
    return NextResponse.json({ favorited: false });
  }
}

