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

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

  try {
    const data = await req.json();

    // Map form fields to model fields
    const {
      studentId,
      fullName,
      email,
      phoneNumber,
      gender,
      dateOfBirth,
      nationality,
      aboutYourself,
      profileImage,
      postalCode,
      city,
      country,
      address,
      educations,
      experiences,
      skills,
      languages,
      drivingLicenses,
      hobbies,
      awards,
      projects
    } = data;

    // Validate required fields with better error messages
    const missingFields = [];
    if (!fullName?.trim()) missingFields.push('fullName');
    if (!email?.trim()) missingFields.push('email');
    if (!phoneNumber?.trim()) missingFields.push('phoneNumber');
    if (!gender?.trim()) missingFields.push('gender');
    if (!dateOfBirth?.trim()) missingFields.push('dateOfBirth');
    if (!nationality?.trim()) missingFields.push('nationality');
    if (!city?.trim()) missingFields.push('city');
    if (!country?.trim()) missingFields.push('country');
    if (!address?.trim()) missingFields.push('address');

    if (missingFields.length > 0) {
      return NextResponse.json({ 
        success: false, 
        error: `Missing required fields: ${missingFields.join(', ')}`,
        message: 'Please fill in all required fields marked with *'
      }, { status: 400 });
    }

    // Validate email format
    if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      return NextResponse.json({ 
        success: false, 
        error: 'Invalid email format',
        message: 'Please enter a valid email address'
      }, { status: 400 });
    }

    // Validate gender enum values and convert to proper case
    const validGenders = ['Male', 'Female', 'Other'];
    const normalizedGender = gender.charAt(0).toUpperCase() + gender.slice(1).toLowerCase();
    
    if (!validGenders.includes(normalizedGender)) {
      return NextResponse.json({ 
        success: false, 
        error: 'Invalid gender value',
        message: 'Gender must be Male, Female, or Other'
      }, { status: 400 });
    }

    // Validate date format
    if (!dateOfBirth || isNaN(new Date(dateOfBirth).getTime())) {
      return NextResponse.json({ 
        success: false, 
        error: 'Invalid date format',
        message: 'Please enter a valid date of birth'
      }, { status: 400 });
    }

    // Validate date is not in the future
    const birthDate = new Date(dateOfBirth);
    const today = new Date();
    if (birthDate > today) {
      return NextResponse.json({ 
        success: false, 
        error: 'Invalid date of birth',
        message: 'Date of birth cannot be in the future'
      }, { status: 400 });
    }

    // Convert the date of birth to MySQL format
    const formattedBirthDate = birthDate.toISOString().split('T')[0];

    // Prepare JSON fields for SQL insertion
    const educationDetails = educations ? JSON.stringify(educations) : null;
    const experienceDetails = experiences ? JSON.stringify(experiences) : null;
    const skillsJson = skills ? JSON.stringify(skills) : null;
    const languagesJson = languages ? JSON.stringify(languages) : null;
    const drivingLicensesJson = drivingLicenses ? JSON.stringify(drivingLicenses) : null;
    const hobbiesJson = hobbies ? JSON.stringify(hobbies) : null;
    const awardsJson = awards ? JSON.stringify(awards) : null;
    const projectsJson = projects ? JSON.stringify(projects) : null;

    // Check if student already has a resume
    const [checkStudentID] = await connection.query<RowDataPacket[]>(
      "SELECT * FROM resumes WHERE student_id = ?", 
      [studentId]
    );

    if (checkStudentID.length > 0) {
      // Update existing resume
      const [rows] = await connection.query<ResultSetHeader>(
        `UPDATE resumes 
        SET 
          full_name = ?, 
          email = ?, 
          phone_number = ?, 
          gender = ?, 
          birth_date = ?, 
          nationality = ?, 
          about_yourself = ?, 
          profile_image = ?, 
          postal_code = ?, 
          city = ?, 
          country = ?, 
          address = ?, 
          education_details = ?, 
          experience_details = ?, 
          skills = ?, 
          languages = ?, 
          driving_licence = ?, 
          hobbies_and_interest = ?, 
          awards = ?, 
          projects = ? 
        WHERE student_id = ?`,
        [
          fullName,
          email,
          phoneNumber,
          normalizedGender,
          formattedBirthDate,
          nationality,
          aboutYourself,
          profileImage,
          postalCode,
          city,
          country,
          address,
          educationDetails,
          experienceDetails,
          skillsJson,
          languagesJson,
          drivingLicensesJson,
          hobbiesJson,
          awardsJson,
          projectsJson,
          studentId
        ]
      );
      
      if (rows.affectedRows === 0) {
        return NextResponse.json({ 
          success: false, 
          message: 'Failed to update resume. Please try again.' 
        }, { status: 500 });
      }

      return NextResponse.json({ 
        success: true, 
        message: 'Resume updated successfully!',
        resume: rows 
      });
    } else {
      // Create new resume
      const [rows] = await connection.query<ResultSetHeader>(
        `INSERT INTO resumes (student_id, full_name, email, phone_number, gender, birth_date, nationality, about_yourself, profile_image, postal_code, city, country, address, education_details, experience_details, skills, languages, driving_licence, hobbies_and_interest, awards, projects) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        [
          studentId,
          fullName,
          email,
          phoneNumber,
          normalizedGender,
          formattedBirthDate,
          nationality,
          aboutYourself,
          profileImage,
          postalCode,
          city,
          country,
          address,
          educationDetails,
          experienceDetails,
          skillsJson,
          languagesJson,
          drivingLicensesJson,
          hobbiesJson,
          awardsJson,
          projectsJson
        ]
      );

      if (rows.affectedRows === 0) {
        return NextResponse.json({ 
          success: false, 
          message: 'Failed to create resume. Please try again.' 
        }, { status: 500 });
      }
      
      return NextResponse.json({ 
        success: true, 
        message: 'Resume created successfully!',
        resume: rows 
      });
    }
  } catch (error) {
    console.error('Resume creation error:', error);
    return NextResponse.json({ 
      success: false, 
      error: error.message,
      message: 'An unexpected error occurred. Please try again later.'
    }, { status: 500 });
  } finally {
    connection.release();
  }
}