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 courses by university country
      query = `
        SELECT 
          c.id, 
          c.name, 
          c.popular, 
          c.qualification,
          c.duration,
          c.yearly_fee,
          u.name AS university,
          u.logo AS university_logo,
          con.currency_symbol,
          c.scholarship,
          u.country AS university_country
        FROM courses c
        RIGHT JOIN university_details u ON c.university_id = u.id
          AND u.country = ?
        LEFT JOIN countries con ON con.country = ?
        WHERE c.popular = 1
        GROUP BY c.name  
        ORDER BY c.created_at DESC 
        LIMIT 8`;
      queryParams = [country, country];
    } else {
      // Original query - no country filter
      query = `
        SELECT 
          c.id, 
          c.name, 
          c.popular, 
          c.qualification,
          u.name AS university,
          u.logo AS university_logo
        FROM courses c
        LEFT JOIN university_details u ON c.university_id = u.id
        WHERE c.popular = 1 ORDER BY c.created_at DESC LIMIT 5`;
      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
      }
    );
  }
}