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

export async function GET(request: NextRequest) {
  const connection = await pool.getConnection();

  try {
    const { searchParams } = new URL(request.url);
    const studentId = searchParams.get('student_id');

    if (!studentId) {
      return NextResponse.json(
        { error: 'Student ID is required' },
        { status: 400 }
      );
    }

    const [applications] = await connection.query(
      `SELECT 
        sa.*,
        CASE 
          WHEN sa.type = 'university' AND sa.apply_id IS NOT NULL THEN u.slug
          ELSE NULL
        END as university_slug
       FROM search_apply_now sa
       LEFT JOIN university_details u ON sa.type = 'university' AND sa.apply_id = u.id
       WHERE sa.user_id = ?
       ORDER BY sa.created_at DESC`,
      [studentId]
    );

    return NextResponse.json({ applications });
  } catch (error) {
    console.error('Error fetching applications:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  } finally {
    connection.release();
  }
}