import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';

export async function GET(request: NextRequest) {
  try {
    const session = await getServerSession(authOptions);

    if (!session || !session.user) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }
    const { searchParams } = new URL(request.url);
    const countryId = searchParams.get('countryId') || '';

    const user = session.user as any;

    if (user.role !== 'FREELANCER') {
      return NextResponse.json(
        { error: 'Access denied. Freelancer role required.' },
        { status: 403 }
      );
    }

    if (!prisma) {
      return NextResponse.json({
        success: true,
        data: {
          recommended: 0,
          proposed: 0,
          awarded: 0,
          cancelled: 0,
          completed: 0
        }
      });
    }

    try {
      // Get freelancer's active category subscriptions for RECOMMENDED projects
      const activeCategorySubscriptions = await prisma.categorySubscription.findMany({
        where: {
          userId: user.id,
          status: 'ACTIVE',
          endDate: {
            gte: new Date()
          }
        },
        select: {
          categoryId: true
        }
      });
      
      const subscribedCategoryIds = activeCategorySubscriptions.map(sub => sub.categoryId);

      // Get counts for all statuses
      const [recommendedCount, proposedCount, awardedCount, cancelledCount, completedCount] = await Promise.all([
        // Recommended count - only from subscribed categories
        subscribedCategoryIds.length > 0 ? prisma.project.count({
          where: {
            status: 'OPEN',
            countryId: countryId,
            categoryId: {
              in: subscribedCategoryIds
            },
            NOT: {
              bids: {
                some: {
                  freelancerId: user.id
                }
              }
            }
          }
        }) : Promise.resolve(0),
        prisma.project.count({
          where: {
            bids: {
              some: {
                freelancerId: user.id,
                status: 'PENDING'
              }
            }
          }
        }),
        prisma.project.count({
          where: {
            bids: {
              some: {
                freelancerId: user.id,
                status: 'ACCEPTED'
              }
            }
          }
        }),
        prisma.project.count({
          where: {
            OR: [
              { status: 'CANCELLED' },
              {
                bids: {
                  some: {
                    freelancerId: user.id,
                    status: 'REJECTED'
                  }
                }
              }
            ]
          }
        }),
        prisma.project.count({
          where: {
            status: 'COMPLETED',
            bids: {
              some: {
                freelancerId: user.id,
                status: 'ACCEPTED'
              }
            }
          }
        })
      ]);

      return NextResponse.json({
        success: true,
        data: {
          recommended: recommendedCount,
          proposed: proposedCount,
          awarded: awardedCount,
          cancelled: cancelledCount,
          completed: completedCount
        }
      });

    } catch (dbError) {
      console.error('Database query error:', dbError);
      
      return NextResponse.json({
        success: true,
        data: {
          recommended: 0,
          proposed: 0,
          awarded: 0,
          cancelled: 0,
          completed: 0
        }
      });
    }

  } catch (error) {
    console.error('Error fetching project counts:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}
