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

export async function POST(
  req: NextRequest,
  context: { params: Promise<{ slug: string }> }
) {
  const comingHeaders = req.headers.get("authorization");

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

  try {
    // ✅ Correct way (await params)
    const { slug } = await context.params;

    // 🔹 Get course details
    const [rows] = await pool.query<RowDataPacket[]>(
      `SELECT 
        c.id AS id,
        c.slug AS slug,
        c.name AS name, 
        c.duration AS duration,
        c.duration_type AS duration_type,
        c.yearly_fee AS yearly_fee,
        c.scholarship AS scholarship,
        c.university_id AS university_id,
        c.subject_id AS subject_id,
        c.qualification AS qualification,
        c.languages AS languages,
        ud.name AS university_name,
        ud.logo AS universityLogo,
        ud.intake AS intake,
        ud.address AS location,
        s.name AS subject_name,
        co.currency AS currency,
        co.currency_symbol AS currency_symbol,
        co.consultation_fee AS consultation_fee,
        co.consultation_fee_discount AS consultation_fee_discount,
        (co.consultation_fee - (co.consultation_fee * (co.consultation_fee_discount / 100))) AS consultation_fee_after_discount,
        p.title AS qualification
      FROM courses c
      LEFT JOIN university_details ud ON c.university_id = ud.id
      LEFT JOIN subjects s ON c.subject_id = s.id
      LEFT JOIN countries co ON ud.country = co.country
      LEFT JOIN posts p ON c.qualification = p.id
      WHERE c.slug = ?`,
      [slug]
    );

    if (rows.length === 0) {
      return NextResponse.json(
        {
          success: false,
          message: "There is no course available for this slug",
        },
        { status: 404 }
      );
    }

    const course = rows[0];

    // 🔹 Get related courses
    const [relatedcourse] = await pool.query<RowDataPacket[]>(
      `SELECT 
        c.id AS id,
        c.slug AS slug,
        c.name AS name,
        c.university_id AS university_id,
        ud.logo as university_logo,
        ud.name AS university_name,
        ud.address AS location,
        co.image as flag_image,
        co.country as country_name
      FROM courses c
      LEFT JOIN university_details ud ON c.university_id = ud.id
      LEFT JOIN countries co ON ud.country = co.country
      WHERE c.university_id = ? AND c.id != ? LIMIT 3`,
      [course.university_id, course.id]
    );

    // 🔹 Final response
    return NextResponse.json(
      {
        success: true,
        data: course,
        relatedcourse: relatedcourse.length > 0 ? relatedcourse : [],
      },
      { status: 200 }
    );

  } catch (err: any) {
    console.error(err);

    return NextResponse.json(
      {
        success: false,
        message: err.message || "Internal Server Error",
      },
      { status: 500 }
    );
  }
}