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

export async function GET(request, { params }) {
  const { slug } = await params;
  
  if (!slug) {
    return NextResponse.json(
      { success: false, message: 'Slug parameter is required' },
      { status: 400 }
    );
  }

  const connection = await pool.getConnection();
  try {
    // Get foreign student details by slug
    const [students] = await connection.query(
      `SELECT 
        fs.*,
        c.name as country_name,
        c.phonecode as country_code,
        c.shortname as country_code_short
      FROM foreign_students fs
      LEFT JOIN countries_db c ON fs.country_id = c.id
      WHERE fs.user_slug = ?`,
      [slug]
    );

    if (students.length === 0) {
      return NextResponse.json(
        { success: false, message: 'Foreign student not found' },
        { status: 404 }
      );
    }

    const student = students[0];

    // Get weekly availability schedule
    const [weeklySchedule] = await connection.query(
      `SELECT 
      id,
        day_of_week,
        is_available
      FROM foreign_student_weekly_schedule 
      WHERE foreign_student_id = ?`,
      [student.id]
    );

    // Get time slots for each day
    const availabilityWithSlots = await Promise.all(
      weeklySchedule.map(async (day) => {
        const [timeSlots] = await connection.query(
          `SELECT 
            start_time,
            end_time
          FROM foreign_student_time_slots 
          WHERE weekly_schedule_id = ?
          ORDER BY start_time`,
          [day.id]
        );

        return {
          ...day,
          time_slots: timeSlots.map(slot => ({
            start: slot.start_time.substring(0, 5), // Format HH:MM
            end: slot.end_time.substring(0, 5)
          }))
        };
      })
    );

    // Filter only available days
    const availability = availabilityWithSlots.filter(day => day.is_available === 1);

    // Get education label mapping
    const educationLabels = {
      high_school: 'High School',
      bachelors: "Bachelor's Degree",
      masters: "Master's Degree",
      phd: 'PhD',
      diploma: 'Diploma',
      certificate: 'Certificate'
    };

    // Calculate rating (if you have reviews table in future, add it here)
    // For now, we'll use default values
    const stats = {
      total_sessions: 0,
      completed_sessions: 0,
      completion_rate: 0
    };

    const rating = {
      average: '0.0',
      count: 0
    };

    // Format the response
    const responseData = {
      success: true,
      student: {
        id: student.id,
        name: student.name,
        user_slug: student.user_slug,
        country_id: student.country_id,
        country_name: student.country_name,
        country_code: student.country_code,
        country_code_short: student.country_code_short,
        timezone: student.timezone,
        about_me: student.about_me,
        profile_picture: student.profile_picture,
        hour_rate: parseFloat(student.hour_rate) || 0,
        gender: student.gender,
        experience: student.experience,
        last_education: student.last_education,
        education_label: educationLabels[student.last_education] || student.last_education,
        email_verified: Boolean(student.email_verified),
        is_verified: Boolean(student.is_verified),
        is_active: Boolean(student.is_active),
        created_at: student.created_at,
        updated_at: student.updated_at,
        rating: rating,
        stats: stats
      },
      availability: availability.map(day => ({
        day_of_week: day.day_of_week,
        is_available: day.is_available,
        time_slots: day.time_slots
      }))
    };

    return NextResponse.json(responseData);

  } catch (error) {
    console.error('Error fetching foreign student details:', error);
    return NextResponse.json(
      { success: false, message: 'Failed to fetch student details', error: error.message },
      { status: 500 }
    );
  } finally {
    if (connection) {
      connection.release();
    }
  }
}