// app/api/frontend/eligibility-calculator/config/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { RowDataPacket } from 'mysql2';
import pool from "../../../../../lib/db/db";

export async function GET(req: NextRequest) {
  const connection = await pool.getConnection();
  
  // Check authorization
  const comingHeaders = req.headers.get("authorization");
  if (comingHeaders !== process.env.APP_API_KEY) {
    return NextResponse.json(
      { success: false, message: 'Unauthorized Access' },
      { status: 401 }
    );
  }

  try {
    // Fetch countries with their currencies
    const [countries] = await connection.query<RowDataPacket[]>(
      `SELECT DISTINCT c.id, c.country, c.currency, c.currency_symbol 
       FROM countries c
       INNER JOIN university_details u ON c.country = u.country
       INNER JOIN courses co ON u.id = co.university_id
       ORDER BY c.country ASC`
    );

    // Fetch qualification levels
    const [levels] = await connection.query<RowDataPacket[]>(
      `SELECT id, title FROM posts ORDER BY display_order ASC`
    );

    // Fetch subjects/fields of study
    const [subjects] = await connection.query<RowDataPacket[]>(
      `SELECT id, name FROM subjects ORDER BY name ASC`
    );

    return NextResponse.json(
      {
        success: true,
        data: {
          countries: countries,
          levels: levels,
          subjects: subjects
        }
      },
      { status: 200 }
    );
  } catch (err: any) {
    console.error('Error fetching eligibility config:', err);
    return NextResponse.json(
      {
        success: false,
        message: err.message,
        data: null
      },
      { status: 500 }
    );
  } finally {
    connection.release();
  }
}