// app/api/user-ticket/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 userId = searchParams.get('userId');
        const checked = searchParams.get('checked');
        const hasProducts = searchParams.get('hasProducts');
        const page = parseInt(searchParams.get('page') || '1');
        const limit = parseInt(searchParams.get('limit') || '10');
        const skip = (page - 1) * limit;

        // Build where clause based on filters
        let whereClause: any = {};
        
        if (userId) {
            whereClause.telegramUserId = userId;
        }
        
        // Filter by checked status if provided
        if (checked !== null) {
            whereClause.checked = checked === 'true';
        }
        
        // Get the tickets with pagination
        const userTickets = await prisma.userTicket.findMany({
            where: whereClause,
            include: {
                telegramUser: {
                    include: {
                        userProducts: true
                    }
                },
            },
            orderBy: { createdAt: 'desc' },
            skip,
            take: limit
        });
        
        // Filter by hasProducts if needed
        let filteredTickets = userTickets;
        if (hasProducts !== null) {
            const hasProductsBoolean = hasProducts === 'true';
            filteredTickets = userTickets.filter(ticket => {
                const productsCount = ticket.telegramUser.userProducts.length;
                return hasProductsBoolean ? productsCount > 0 : productsCount === 0;
            });
        }
        
        // Get total count for pagination
        const totalCount = await prisma.userTicket.count({
            where: whereClause
        });
        
        return NextResponse.json({
            tickets: filteredTickets,
            pagination: {
                totalCount,
                totalPages: Math.ceil(totalCount / limit),
                currentPage: page,
                pageSize: limit
            }
        });
    } catch (error) {
        console.error('Error fetching user tickets:', error);
        return NextResponse.json({ error: 'Error fetching user tickets' }, { status: 500 });
    }
}