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

export async function POST(request: NextRequest){

    // Authorization check
    const comingHeaders = request.headers.get("authorization");

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

    try{

        const { searchParams } = new URL(request.url);
        const search = searchParams.get('query') || '';

        const searchPattern = `%${search}%`;

        const [rows] = await pool.query<RowDataPacket[]>(
            `SELECT
            c.*,
            u.logo as image,
            u.name as university,
            p.title as qualification,
            c.yearly_fee as fee_with_symbol,
            c.application_fee as application_fee_with_symbol
            FROM courses c
            LEFT JOIN university_details u ON c.university_id = u.id
            LEFT JOIN posts p ON p.id = c.qualification
            WHERE c.name LIKE ? LIMIT 20`, 
            [searchPattern]
        );

        return NextResponse.json(
            {
                success: true,
                message: "Results found",
                data: rows
            },
            {
                status: 200
            }
        )

    } catch (error) {
        console.error('Search error:', error);
        return NextResponse.json(
            {
                success: false,
                message: "Error fetching the results"
            },
            {
                status: 500
            }
        )
    }
}