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

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const parentId = searchParams.get('parentId');
    const active = searchParams.get('active');
    const countryId = searchParams.get('countryId') || '';

    const whereClause: any = {};

    if (parentId) {
      whereClause.parentId = parentId;
    } else if (parentId === 'null') {
      whereClause.parentId = null;
    }

    if (active !== null) {
      whereClause.isActive = active === 'true';
    }

    const categories = await prisma.category.findMany({
      where: whereClause,
      include: {
        children: {
          where: {
            isActive: true
          }
        },
        _count: {
          select: {
            projects: {
              where: {
                countryId: countryId,
                status: 'OPEN'
              }
            },
            profiles: true
          }
        }
      },
      orderBy: {
        name: 'asc'
      }
    });

    return NextResponse.json(categories);

  } catch (error) {
    console.error('Categories fetch error:', error);
    return NextResponse.json(
      { message: 'Internal server error' },
      { status: 500 }
    );
  }
} 