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

export async function GET(req: NextRequest) {
    // Check authorization header
    const incomingHeaders = req.headers.get("authorization");

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

    try {
        const connection = await pool.getConnection();
        
        const [rows] = await connection.query<RowDataPacket[]>(
            `SELECT 
                c.id, 
                c.country, 
                c.image,
                COUNT(DISTINCT ud.id) AS university_count,
                COUNT(DISTINCT nc.id) AS course_count
            FROM countries c
            LEFT JOIN university_details ud ON c.country = ud.country AND ud.active = true
            LEFT JOIN courses nc ON ud.id = nc.university_id AND nc.active = true
            GROUP BY c.id, c.country, c.image
            HAVING university_count > 0 AND course_count > 0`
        );
        
        connection.release();

        if (rows.length === 0) {
            return NextResponse.json(
                {
                    success: false,
                    message: "No countries found"
                },
                {
                    status: 404
                }
            );
        }
        
        return NextResponse.json(
            {
                success: true,
                message: "Countries found",
                data: rows
            },
            {
                status: 200,
                headers: {
                    'Cache-Control': 'public, max-age=3600',
                },
            }
        );
    } catch (error) {
        console.error('Error fetching countries:', error);
        return NextResponse.json(
            {
                success: false,
                message: 'Internal server error'
            },
            {
                status: 500
            }
        );
    }
}