// app/api/internal/student/foreign-students/route.js
import pool from '../../../../../lib/db/db';
import { NextRequest, NextResponse } from 'next/server';
import { RowDataPacket } from 'mysql2';
import jwt from 'jsonwebtoken';

export async function GET(req: NextRequest) {
  const connection = await pool.getConnection();
  
  try {
    // Get token from cookie
    const token = req.cookies.get('university-token')?.value;
    
    if (!token) {
      connection.release();
      return NextResponse.json(
        { success: false, message: 'Authentication required' },
        { status: 401 }
      );
    }

    // Verify token
    let decoded;
    try {
      decoded = jwt.verify(token, process.env.JWT_SECRET as string);
    } catch (err) {
      connection.release();
      return NextResponse.json(
        { success: false, message: 'Invalid or expired token' },
        { status: 401 }
      );
    }

    if (decoded.role !== 'student') {
      connection.release();
      return NextResponse.json(
        { success: false, message: 'Access denied' },
        { status: 403 }
      );
    }

    // Fetch active foreign students with country name
    const [students] = await connection.query<RowDataPacket[]>(
      `SELECT 
        fs.id,
        fs.name,
        fs.country_id,
        fs.about_me,
        fs.profile_picture,
        fs.hour_rate,
        fs.gender,
        fs.experience,
        fs.last_education,
        fs.timezone,
        c.name as country_name
       FROM foreign_students fs
       LEFT JOIN countries_db c ON fs.country_id = c.id
       WHERE fs.is_active = 1
       ORDER BY fs.name ASC`
    );

    connection.release();

    return NextResponse.json({
      success: true,
      message: 'Foreign students fetched successfully',
      students: students
    }, { status: 200 });

  } catch (err: any) {
    if (connection) connection.release();
    console.error('Get foreign students error:', err);
    return NextResponse.json(
      { success: false, message: 'Failed to fetch foreign students' },
      { status: 500 }
    );
  }
}