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

type PageProps = {
  params: Promise<{
    id: string;
  }>;
};

export async function POST(req: NextRequest, { params }: PageProps) {

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

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

  const connection = await pool.getConnection();

  try {
    const {id} = await params // Access query parameter
    
    // Updated query with LEFT JOIN to get courses
    const [rows] = await connection.query<RowDataPacket[]>(
      `SELECT 
        ud.*,
        co.currency AS currency,
        co.consultation_fee AS consultation_fee,
        co.currency_symbol AS currency_symbol,
        co.consultation_fee_discount AS consultation_fee_discount,
        co.currency AS currency,
        (co.consultation_fee - (co.consultation_fee * (co.consultation_fee_discount / 100))) AS consultation_fee_after_discount,
        c.id AS course_id,
        c.name AS course_name,
        c.qualification AS course_qualification,
        c.duration AS course_duration,
        c.yearly_fee AS course_tuition_fee,
        c.application_fee AS course_application_fee,
        c.languages AS course_language,
        c.subject_id AS course_subject_id,
        c.created_at AS course_created_at
      FROM university_details ud
      LEFT JOIN countries co ON ud.country = co.country
      LEFT JOIN courses c ON ud.id = c.university_id
      WHERE ud.id = ?`, [id])

    if(rows.length > 0) {
        // Group courses data
        const courses = rows
          .filter(row => row.course_id) // Only include rows with courses
          .map(row => ({
            id: row.course_id,
            name: row.course_name,
            qualification: row.course_qualification,
            duration: row.course_duration,
            tuition_fee: row.course_tuition_fee,
            application_fee: row.course_application_fee,
            language: row.course_language,
            subject_id: row.course_subject_id,
            created_at: row.course_created_at,
            currency_symbol: row.currency_symbol,
            university_id: row.id
          }));

        // Get unique university data (first row)
        const universityData = {
          ...rows[0],
          // Remove course fields from university data
          course_id: undefined,
          course_name: undefined,
          course_qualification: undefined,
          course_duration: undefined,
          course_tuition_fee: undefined,
          course_application_fee: undefined,
          course_language: undefined,
          course_subject_id: undefined,
          course_created_at: undefined
        };

        const [relatedUniversities] = await connection.query<RowDataPacket[]>(
          "SELECT id, name, logo, feature_image FROM university_details WHERE id != ? AND popular = 1 ORDER BY created_at DESC LIMIT 3", 
          [id]
        )

        return NextResponse.json({
          success: true,
          data: universityData,
          courses: courses,
          courses_count: courses.length,
          realtedUniversities: relatedUniversities.length > 0 ? relatedUniversities : []
        }, { status: 200 });

    } else {
        return NextResponse.json({
          success: false,
          message: "You Enter invalid University",
          data: []
        }, { status: 404 });
    }

  } catch (err: any) {
    console.log(err)
    return NextResponse.json({
      success: false,
      message: err.message,
    }, { status: 500 });
  } finally {
    connection.release();
  }
}