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

export async function GET(req: NextRequest) {
  try {
    if (!prisma) {
      return NextResponse.json(
        { error: 'Database connection not available' },
        { status: 503 }
      );
    }

    const { searchParams } = new URL(req.url);
    const countryId = searchParams.get('countryId') || '';

    // Get top 8 categories with project counts
    const categories = await prisma.category.findMany({
      where: {
        isActive: true
      },
      select: {
        id: true,
        name: true,
        slug: true,
        description: true,
        icon: true,
        _count: {
          select: {
            projects: {
              where: {
                countryId: countryId,
                status: 'OPEN'
              }
            }
          }
        }
      },
      orderBy: [
        {
          projects: {
            _count: 'desc'
          }
        },
        {
          name: 'asc'
        }
      ],
      take: 8
    });

    // Format the response
    const formattedCategories = categories.map(category => ({
      id: category.id,
      name: category.name,
      slug: category.slug,
      description: category.description,
      icon: category.icon,
      image: `/assets/image/category/${category.icon}`,
      projectCount: category._count.projects
    }));

    return NextResponse.json({
      success: true,
      data: formattedCategories
    });

  } catch (error) {
    console.error('Error fetching featured categories:', error);
    
    return NextResponse.json(
      { 
        error: error instanceof Error ? error.message : 'Failed to fetch featured categories',
        type: 'server_error'
      },
      { status: 500 }
    );
  }
}