// app/api/user-products/route.ts
import { NextResponse } from 'next/server';

import { prisma } from '@/lib/prisma';

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url);
    const productId = searchParams.get('productId');
    const status = searchParams.get('status');
    const userId = searchParams.get('userId');
    const searchTerm = searchParams.get('search');


    // Build where clause with filters
    let whereClause: any = {};

    if (productId) {
      whereClause.productId = parseInt(productId);
    }

    if (status) {
      whereClause.challengeStatus = status;
    }

    if (userId) {
      whereClause.userId = userId;
    }

    if (searchTerm) {
      whereClause.OR = [
        {
          user: {
            OR: [
              { firstName: { contains: searchTerm, mode: 'insensitive' } },
              { username: { contains: searchTerm, mode: 'insensitive' } },
              { telegramId: { contains: searchTerm, mode: 'insensitive' } }
            ]
          }
        },
        {
          product: {
            plan: { contains: searchTerm, mode: 'insensitive' }
          }
        }
      ];
    }

    const userProducts = await prisma.userProduct.findMany({
      where: whereClause,
      include: {
        user: true,
        product: true
      },
      orderBy: { createdAt: 'desc' }
    });

    return NextResponse.json(userProducts);
  } catch (error) {
    console.error('Error fetching user products:', error);
    return NextResponse.json({ error: 'Error fetching user products' }, { status: 500 });
  }
}