import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { Prisma } from '@prisma/client';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const userId = searchParams.get('userId');
    const itemType = searchParams.get('itemType');
    const page = parseInt(searchParams.get('page') || '1');
    const limit = parseInt(searchParams.get('limit') || '20');

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

    const where: Prisma.FavouriteWhereInput = {
      userId,
    };

    if (itemType) where.itemType = itemType;

    const skip = (page - 1) * limit;

    const [favourites, total] = await Promise.all([
      db.favourite.findMany({
        where,
        orderBy: { createdAt: 'desc' },
        skip,
        take: limit,
      }),
      db.favourite.count({ where }),
    ]);

    // Parse itemData JSON for each favourite
    const parsedFavourites = favourites.map((f) => ({
      ...f,
      itemData: JSON.parse(f.itemData),
    }));

    return NextResponse.json({
      favourites: parsedFavourites,
      pagination: {
        page,
        limit,
        total,
        totalPages: Math.ceil(total / limit),
      },
    });
  } catch (error) {
    console.error('Favourites GET error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { userId, itemType, itemId, itemData } = body;

    if (!userId || !itemType || !itemId) {
      return NextResponse.json(
        { error: 'Missing required fields: userId, itemType, itemId' },
        { status: 400 }
      );
    }

    // Check if already favourited
    const existing = await db.favourite.findUnique({
      where: {
        userId_itemType_itemId: { userId, itemType, itemId },
      },
    });

    if (existing) {
      return NextResponse.json(
        { error: 'Already added to favourites' },
        { status: 409 }
      );
    }

    const favourite = await db.favourite.create({
      data: {
        userId,
        itemType,
        itemId,
        itemData: itemData ? JSON.stringify(itemData) : '{}',
      },
    });

    return NextResponse.json({ favourite }, { status: 201 });
  } catch (error) {
    console.error('Favourites POST error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}

export async function DELETE(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const userId = searchParams.get('userId');
    const itemType = searchParams.get('itemType');
    const itemId = searchParams.get('itemId');

    if (!userId || !itemType || !itemId) {
      return NextResponse.json(
        { error: 'Missing required fields: userId, itemType, itemId' },
        { status: 400 }
      );
    }

    const favourite = await db.favourite.findUnique({
      where: {
        userId_itemType_itemId: { userId, itemType, itemId },
      },
    });

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

    await db.favourite.delete({
      where: {
        userId_itemType_itemId: { userId, itemType, itemId },
      },
    });

    return NextResponse.json({ message: 'Removed from favourites' });
  } catch (error) {
    console.error('Favourites DELETE error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}
