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


export async function POST(request: NextRequest){

    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.intake as intake,
                ud.accommodation as accommodation,
                ud.address as address,
                ud.languages as languages,
                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.university_type as type,
                ud.total_students as total_students,
                ud.international_student as international_student,
                COUNT(c.id) as course_count
            FROM university_details ud
            LEFT JOIN courses c ON ud.id = c.university_id
            WHERE is_active = 1 AND ud.name LIKE ?
            GROUP BY ud.id
            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,
                    accommodation: r.accommodation,
                    address: r.address,
                    intake: r.intake,
                    course_count: r.course_count,
                    languages: r.languages,
                    website: r.website,
                    type: r.type,
                    total_students: r.total_students,
                    international_student: r.international_student,
                    location: `${r.city ? r.city + ', ' : ''}${r.country}`,
                }
            })
        ]

        return NextResponse.json(
            {
                message: "Find",
                data: newRows
            },
            {
                status: 200
            }
        )

    } catch (erroe){
        return NextResponse.json(
            {
                message: "Error Fetching the results",
                success: false
            },
            {
                status: 500
            }
        )
    }
}