// app/api/appapis/preferences/route.js
import { NextRequest, NextResponse } from 'next/server';
import pool from '../../../../lib/db/db';
import { verifyAuthentication } from '../../../utils/verifyAuthentication';
import { ResultSetHeader, RowDataPacket } from 'mysql2';

interface TokenInterface {
  id: number;
  userId?: number;
  email?: string;
  role?: string;
}

export async function OPTIONS() {
  return NextResponse.json({}, { status: 200 });
}

export async function POST(request: NextRequest) {
  const connection = await pool.getConnection();
  
  try {
    const authHeader = request.headers.get('authorization');
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return NextResponse.json({
        success: false,
        message: "No valid authorization header found"
      }, { status: 401 });
    }

    const token = authHeader.substring(7);
    const authResult = await verifyAuthentication(token);
    
    if (authResult instanceof NextResponse) {
      return authResult;
    }
    
    const decoded = authResult as TokenInterface;
    
    if (!decoded || !decoded.id) {
      return NextResponse.json({
        success: false,
        message: "Invalid token - no user ID found"
      }, { status: 401 });
    }

    // Check if user is authorized (student, consultant, or foreign-student)
    if (decoded.role !== "student" && decoded.role !== "consultant" && decoded.role !== "foreign-student") {
      return NextResponse.json({
        success: false,
        message: "You are not authorized to perform this action"
      }, { status: 401 });
    }

    const body = await request.json();
    const {
      qualification_id,
      subjects_selected,
      cgpa,
      budget,
      english_test_type,
      english_test_score,
    } = body;

    await connection.beginTransaction();

    // Determine which ID to use based on role
    const userId = decoded.id;
    const isForeignStudent = decoded.role === "foreign-student";

    // Check if preferences already exist
    const [existingPrefs] = await connection.query<RowDataPacket[]>(
      `SELECT id FROM app_preferences WHERE ${isForeignStudent ? 'foreign_student_id' : 'user_id'} = ?`,
      [userId]
    );

    let result;
    if (existingPrefs.length > 0) {
      // Update existing preferences
      [result] = await connection.query<ResultSetHeader>(
        `UPDATE app_preferences 
         SET 
          qualification_id = ?,
          subjects_selected = ?,
          cgpa = ?,
          budget = ?,
          english_test_type = ?,
          english_test_score = ?,
          updated_at = NOW()
         WHERE ${isForeignStudent ? 'foreign_student_id' : 'user_id'} = ?`,
        [
          qualification_id || null,
          subjects_selected ? JSON.stringify(subjects_selected) : null,
          cgpa || null,
          budget || null,
          english_test_type || null,
          english_test_score || null,
          userId
        ]
      );
    } else {
      // Insert new preferences
      [result] = await connection.query<ResultSetHeader>(
        `INSERT INTO app_preferences (
          ${isForeignStudent ? 'foreign_student_id' : 'user_id'}, 
          qualification_id, 
          subjects_selected, 
          cgpa, 
          budget, 
          english_test_type, 
          english_test_score, 
          created_at, 
          updated_at
        ) VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), NOW())`,
        [
          userId,
          qualification_id || null,
          subjects_selected ? JSON.stringify(subjects_selected) : null,
          cgpa || null,
          budget || null,
          english_test_type || null,
          english_test_score || null
        ]
      );
    }

    await connection.commit();

    return NextResponse.json({
      success: true,
      message: "Preferences saved successfully"
    }, { status: 200 });

  } catch (error) {
    await connection.rollback();
    console.error('Save preferences error:', error);
    return NextResponse.json({
      success: false,
      message: "Internal server error"
    }, { status: 500 });
  } finally {
    connection.release();
  }
}

export async function GET(request: NextRequest) {
  const connection = await pool.getConnection();
  
  try {
    const authHeader = request.headers.get('authorization');
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return NextResponse.json({
        success: false,
        message: "No valid authorization header found"
      }, { status: 401 });
    }

    const token = authHeader.substring(7);
    const authResult = await verifyAuthentication(token);
    
    if (authResult instanceof NextResponse) {
      return authResult;
    }
    
    const decoded = authResult as TokenInterface;
    
    if (!decoded || !decoded.id) {
      return NextResponse.json({
        success: false,
        message: "Invalid token - no user ID found"
      }, { status: 401 });
    }

    // Determine which ID to use based on role
    const userId = decoded.id;
    const isForeignStudent = decoded.role === "foreign-student";

    // Check if user exists in appropriate table
    if (isForeignStudent) {
      const [foreignStudentExists] = await connection.query<RowDataPacket[]>(
        "SELECT id FROM foreign_students WHERE id = ? AND is_active = 1",
        [userId]
      );
      
      if (foreignStudentExists.length === 0) {
        return NextResponse.json({
          success: false,
          message: "Foreign student not found or inactive"
        }, { status: 404 });
      }
    }

    // Get preferences
    const [preferences] = await connection.query<RowDataPacket[]>(
      `SELECT 
        qualification_id,
        subjects_selected,
        cgpa,
        budget,
        english_test_type,
        english_test_score
      FROM app_preferences 
      WHERE ${isForeignStudent ? 'foreign_student_id' : 'user_id'} = ?`,
      [userId]
    );

    if (preferences.length === 0) {
      return NextResponse.json({
        success: true,
        data: null,
        userType: decoded.role
      }, { status: 200 });
    }

    // Parse subjects_selected if it exists
    let subjectsSelected = [];
    if (preferences[0].subjects_selected) {
      try {
        subjectsSelected = typeof preferences[0].subjects_selected === 'string'
          ? JSON.parse(preferences[0].subjects_selected)
          : preferences[0].subjects_selected;
      } catch (e) {
        console.error('Error parsing subjects_selected:', e);
      }
    }

    return NextResponse.json({
      success: true,
      data: {
        qualification_id: preferences[0].qualification_id,
        subjects_selected: subjectsSelected,
        cgpa: preferences[0].cgpa,
        budget: preferences[0].budget,
        english_test_type: preferences[0].english_test_type,
        english_test_score: preferences[0].english_test_score,
      },
      userType: decoded.role
    }, { status: 200 });

  } catch (error) {
    console.error('Get preferences error:', error);
    return NextResponse.json({
      success: false,
      message: "Internal server error"
    }, { status: 500 });
  } finally {
    connection.release();
  }
}
