// app/api/countries/route.ts
import { NextRequest, NextResponse } from 'next/server';
import pool from '../../../../lib/db/db';
import { RowDataPacket } from "mysql2";

export async function GET(req: NextRequest) {

    const connection = await pool.getConnection();

    const commingHeaders = req.headers.get("authorization");

    if(commingHeaders !== process.env.APP_API_KEY)
    {
        return NextResponse.json(
            { success: false, message: 'Unauthorized Access' },
            { status: 401 }
        );
    }

    try {
        let sqlQuery;

        
        sqlQuery = `
            SELECT 
            id, 
            name, 
            slug, 
            logo,
            country,
            city,
            country as location
            FROM university_details 
            WHERE popular = 1 AND is_active = 1
            ORDER BY created_at DESC 
            LIMIT 4`;

        const [universities] = await connection.query<RowDataPacket[]>(sqlQuery);

        if(universities.length === 0) {
            return NextResponse.json({
                success: false,
                message: 'No universities found',
                data: []
            });
        }

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

    } catch (error) {
        console.error('Database error fetching popular universities:', error);
        return NextResponse.json({
        success: false,
        message: error.message,
        data: []
        });
    } finally {
        connection.release();
    }
}
