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 
            ud.id as id,
            ud.name as name,
            ud.slug as slug,
            ud.logo as image,
            ud.city as city,
            ud.country as country,
            ud.ranking as ranking,
            ud.scholarship as scholarship,
            ud.languages as language,
            ud.founded_in as founded,
            ud.phone_no as phone,
            ud.website as website,
            ud.total_students as total_students,
            ud.international_student as international_student
            FROM university_details ud
            WHERE name LIKE ? LIMIT 20`, [searchPattern]);

        const newRows = [
            ...rows.map((r: any) => {
                return {
                    id: r.id,
                    name: r.name,
                    slug: r.slug,
                    image: r.image,
                    ranking: r.ranking,
                    scholarship: r.scholarship,
                    language: r.language,
                    founded: r.founded,
                    phone: r.phone,
                    website: r.website,
                    total_students: r.total_students,
                    international_student: r.international_student,
                    location: `${r.city ? r.city + ', ' : ''}${r.country}`,
                }
            })
        ]

        console.log(newRows)

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

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