// app/api/courses/popular/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 comingHeaders = req.headers.get("authorization");

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

    try {
        // Get country from query parameters
        const { searchParams } = new URL(req.url);
        const country = searchParams.get('country');

        let sqlQuery;
        let queryParams: any[] = [];

        if (country) {
            // Filter courses by university country
            sqlQuery = `
                SELECT 
                    c.id, 
                    c.slug as slug,
                    c.name, 
                    c.popular, 
                    c.qualification,
                    u.name AS university,
                    u.logo AS university_logo,
                    u.country AS university_country,
                    u.country AS location,
                    u.slug as university_slug
                FROM courses c
                RIGHT JOIN university_details u ON c.university_id = u.id
                WHERE u.country = ?
                GROUP BY c.id, u.name, u.logo, u.country  
                ORDER BY c.created_at DESC 
                LIMIT 8`;
            queryParams = [country];
        } else {
            // Original query - no country filter (popular courses)
            sqlQuery = `
                SELECT 
                    c.id, 
                    c.name, 
                    c.slug as slug,
                    c.popular, 
                    c.qualification,
                    u.name AS university,
                    u.logo AS university_logo,
                    u.country AS location,
                    u.slug as university_slug
                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 [courses] = await connection.query<RowDataPacket[]>(sqlQuery, queryParams);

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

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

    } catch (error) {
        console.error('Database error fetching popular courses:', error);
        return NextResponse.json({
            success: false,
            message: error instanceof Error ? error.message : 'Unknown error occurred',
            data: []
        }, { status: 500 });
    } finally {
        connection.release();
    }
}