// app/api/appapis/resumes/route.ts
import { RowDataPacket } from 'mysql2';
import pool from '../../../../lib/db/db';
import { NextResponse } from 'next/server';
import jwt from 'jsonwebtoken';

// CORS headers
const corsHeaders = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
  'Access-Control-Allow-Headers': 'Content-Type, Authorization, x-api-key, X-API-Key, api_key',
  'Access-Control-Allow-Credentials': 'true',
  'Access-Control-Max-Age': '86400',
};

export async function OPTIONS() {
  return new NextResponse(null, {
    status: 204,
    headers: corsHeaders,
  });
}

// Helper function to verify Bearer token with JWT
async function verifyBearerToken(authHeader: string | null): Promise<{ isValid: boolean; userId?: string; userData?: any; error?: string }> {
  if (!authHeader || !authHeader.startsWith('Bearer ')) {
    return { isValid: false, error: 'No valid authorization header found' };
  }

  const token = authHeader.substring(7);
  
  try {
    // Verify JWT token
    const decoded = jwt.verify(token, process.env.JWT_SECRET || 'your_jwt_secret_key') as any;
    
    if (!decoded || !decoded.id) {
      return { isValid: false, error: 'Invalid token - no user ID found' };
    }
    
    // Check if user is a student
    if (decoded.role !== 'student') {
      return { isValid: false, error: 'User is not authorized as a student' };
    }
    
    return { 
      isValid: true, 
      userId: decoded.id.toString(),
      userData: decoded
    };
  } catch (error: any) {
    console.error('Token verification error:', error.message);
    return { isValid: false, error: 'Token verification failed' };
  }
}

export async function GET(req: Request) {
  const authHeader = req.headers.get("authorization");
  
  // Verify Bearer token
  const tokenResult = await verifyBearerToken(authHeader);
  if (!tokenResult.isValid) {
    return NextResponse.json(
      { success: false, message: tokenResult.error || 'Unauthorized Access' },
      { status: 401, headers: corsHeaders }
    );
  }

  const connection = await pool.getConnection();
  const { searchParams } = new URL(req.url);
  const std = searchParams.get('stId');
  const i = searchParams.get('i');
  let student_id = std || i;

  if (!student_id) {
    return NextResponse.json({ error: 'Missing student id' }, { 
      status: 400,
      headers: corsHeaders 
    });
  }

  try {
    // Verify that the authenticated user owns this resume
    if (tokenResult.userId && tokenResult.userId !== student_id) {
      return NextResponse.json({ error: 'Unauthorized: You can only access your own resume' }, { 
        status: 403,
        headers: corsHeaders 
      });
    }

    const [rows] = await connection.query<RowDataPacket[]>(
      'SELECT * FROM resumes WHERE student_id = ? LIMIT 1',
      [student_id]
    );

    if (rows.length === 0) {
      return NextResponse.json({ error: 'Resume not found' }, { 
        status: 404,
        headers: corsHeaders 
      });
    }

    const resume = rows[0];

    if (std) {
      let count = 0;
      if (resume.link_status && !isNaN(Number(resume.link_status))) {
        count = Number(resume.link_status);
      }

      if (count >= 1000) {
        return NextResponse.json({ error: 'Edit limit reached' }, { 
          status: 403,
          headers: corsHeaders 
        });
      }

      await connection.query(
        'UPDATE resumes SET link_status = ? WHERE id = ?',
        [String(count + 1), resume.id]
      );
    }

    const parseField = (f: any) => {
      try {
        if (!f) return null;
        return JSON.parse(f);
      } catch {
        return f;
      }
    };

    const result = {
      id: resume.id,
      studentId: resume.student_id,
      fullName: resume.full_name,
      email: resume.email,
      emailStatus: resume.email_status,
      link_status: resume.link_status,
      phoneNumber: resume.phone_number,
      gender: resume.gender,
      dateOfBirth: resume.birth_date,
      nationality: resume.nationality,
      aboutYourself: resume.about_yourself,
      profileImage: resume.profile_image,
      postalCode: resume.postal_code,
      city: resume.city,
      country: resume.country,
      address: resume.address,
      education_details: parseField(resume.education_details),
      experience_details: parseField(resume.experience_details),
      skills: parseField(resume.skills),
      languages: parseField(resume.languages),
      driving_licence: parseField(resume.driving_licence),
      hobbies_and_interest: parseField(resume.hobbies_and_interest),
      awards: parseField(resume.awards),
      projects: parseField(resume.projects),
      motherLanguage: resume.mother_language,
      createdAt: resume.created_at,
      updatedAt: resume.updated_at,
    };

    return NextResponse.json(result, { headers: corsHeaders });
  } catch (error) {
    console.error(error);
    return NextResponse.json({ error: 'Internal Server Error' }, { 
      status: 500,
      headers: corsHeaders 
    });
  } finally {
    connection.release();
  }
}

export async function POST(req: Request) {
  const authHeader = req.headers.get("authorization");
  
  // Verify Bearer token
  const tokenResult = await verifyBearerToken(authHeader);
  if (!tokenResult.isValid) {
    return NextResponse.json(
      { success: false, message: tokenResult.error || 'Unauthorized Access' },
      { status: 401, headers: corsHeaders }
    );
  }

  const connection = await pool.getConnection();

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

    const {
      studentId,
      fullName,
      email,
      phoneNumber,
      gender,
      dateOfBirth,
      nationality,
      aboutYourself,
      profileImage,
      postalCode,
      city,
      country,
      address,
      education_details,
      experience_details,
      skills,
      languages,
      driving_licence,
      hobbies_and_interest,
      awards,
      projects
    } = data;

    // Verify that the authenticated user owns this resume
    if (tokenResult.userId && tokenResult.userId !== studentId?.toString()) {
      return NextResponse.json({ 
        success: false, 
        error: 'Unauthorized: You can only modify your own resume'
      }, { status: 403, headers: corsHeaders });
    }

    console.log('Received resume data for student:', studentId);
    console.log('Authenticated user:', tokenResult.userId);

    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, headers: corsHeaders });
    }

    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, headers: corsHeaders });
    }

    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, headers: corsHeaders });
    }

    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, headers: corsHeaders });
    }

    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, headers: corsHeaders });
    }

    const formattedBirthDate = birthDate.toISOString().split('T')[0];

    const educationDetails = education_details ? JSON.stringify(education_details) : null;
    const experienceDetails = experience_details ? JSON.stringify(experience_details) : null;
    const skillsJson = skills ? JSON.stringify(skills) : null;
    const languagesJson = languages ? JSON.stringify(languages) : null;
    const drivingLicensesJson = driving_licence ? JSON.stringify(driving_licence) : null;
    const hobbiesJson = hobbies_and_interest ? JSON.stringify(hobbies_and_interest) : 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
      await connection.query(
        `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
        ]
      );
      
      console.log('Resume updated successfully for student:', studentId);
      
      return NextResponse.json({ 
        success: true, 
        message: 'Resume updated successfully!'
      }, { headers: corsHeaders });
    } else {
      // Create new resume
      await connection.query(
        `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
        ]
      );
      
      console.log('Resume created successfully for student:', studentId);
      
      return NextResponse.json({ 
        success: true, 
        message: 'Resume created successfully!'
      }, { headers: corsHeaders });
    }
  } catch (error: any) {
    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, headers: corsHeaders });
  } finally {
    connection.release();
  }
}