import { NextRequest, NextResponse } from 'next/server';
import { RowDataPacket } from 'mysql2';
import pool from "../../../../lib/db/db"

export async function POST(req: NextRequest) {
  try {
    // Check if request has body and country parameter
    let country = null;
    try {
      const body = await req.json();
      country = body.country;
    } catch (e) {
      // If no JSON body or invalid JSON, continue with original behavior
    }
    
    let query, queryParams;
    
    if (country) {
      // Filter universities by country field - FIXED SQL SYNTAX
      query = `
        SELECT 
          ud.id, 
          ud.name, 
          ud.slug, 
          ud.logo,
          ud.country,
          ud.city,
          ud.ranking,
          ud.scholarship,
          COUNT(DISTINCT c.id) as courses_count
        FROM university_details ud
        LEFT JOIN courses c ON c.university_id = ud.id
        WHERE ud.country = ? AND ud.popular = 1
        GROUP BY ud.id, ud.name, ud.slug, ud.logo, ud.country, ud.city
        ORDER BY ud.created_at DESC 
        LIMIT 8`;
      queryParams = [country];
    } else {
      // Original query - no country filter
      query = "SELECT id, name, slug, logo FROM university_details WHERE popular = 1 ORDER BY created_at DESC LIMIT 4";
      queryParams = [];
    }

    const [rows] = await pool.query<RowDataPacket[]>(query, queryParams);

    if(rows.length > 0) {
      return NextResponse.json(
        {
          success: true,
          data: rows
        },
        {
          status: 200
        }
      );
    } else {
      return NextResponse.json(
        {
          success: false,
          message: "No University Found"
        },
        {
          status: 200
        }
      );
    }

  } catch (err: any) {
    return NextResponse.json(
      {
        success: false,
        message: err.message
      },
      {
        status: 500
      }
    );
  }
}