import { NextRequest, NextResponse } from "next/server";
import { verifyAuthentication } from "../../../utils/verifyAuthentication";
import { RowDataPacket } from "mysql2";
import pool from "../../../../lib/db/db";

  export async function POST(request: NextRequest) {
    // Check authorization header
    const incomingHeaders = request.headers.get("authorization");

    if (incomingHeaders !== process.env.APP_API_KEY) {
        return NextResponse.json(
            { success: false, message: 'Unauthorized Access' },
            { status: 401 }
        );
    }


  try {
    const token = request.cookies.get("university-token")?.value || null;
    const decoded = await verifyAuthentication(token);

    if (decoded instanceof NextResponse) {
      return NextResponse.json(
        { success: false, message: "Unauthorized" },
        { status: 401 }
      );
    }

    if (!decoded) {
      return NextResponse.json(
        { success: false, message: "Unauthorized" },
        { status: 401 }
      );
    }

    // ✅ FIXED QUERY: JOIN with consultants table
    const [checkUser] = await pool.query<RowDataPacket[]>(
      `SELECT 
        u.*,
        c.profile_picture,
        c.nationality,
        c.city,
        c.state,
        c.company_name,
        c.designation,
        c.phone as consultant_phone,
        c.address,
        c.employeeno as number_of_employees,
        c.target_countries,
        c.services,
        c.specialization,
        c.languages,
        c.consultation_fee,
        c.response_time,
        c.digital_only,
        c.availability,
        c.comment,
        c.average_rating,
        c.rating_count,
        c.active_profile,
        c.profile_status,
        c.profile_completed_date,
        c.approval_requested_date,
        c.approved_date,
        c.rejection_reason
      FROM users u
      LEFT JOIN consultants c ON u.id = c.user_id
      WHERE u.id = ? AND u.user_type IN ('student', 'consultant')`,
      [decoded.id]
    );

    if (checkUser.length === 0) {
      return NextResponse.json(
        { success: false, message: "Unauthorized" },
        { status: 401 }
      );
    }

    const userData = checkUser[0];
    
    
    // Parse JSON fields safely
    const parseJSONField = (value) => {
      if (!value || value === 'null' || value === '""' || value === '[]') return [];
      try {
        return JSON.parse(value);
      } catch {
        return Array.isArray(value) ? value : [];
      }
    };

    // Calculate completeness percentage
    const calculateCompleteness = (data) => {
      let filledFields = 0;
      let totalFields = 0;

      const requiredFields = [
        { field: 'first_name', weight: 5 },
        { field: 'last_name', weight: 5 },
        { field: 'designation', weight: 5 },
        { field: 'email', weight: 5 },
        { field: 'phone', weight: 5, useField: data.consultant_phone || data.phone },
        { field: 'company_name', weight: 5 },
        { field: 'address', weight: 5 },
        { field: 'number_of_employees', weight: 5 },
        { field: 'nationality', weight: 5 },
        { field: 'state', weight: 5 },
        { field: 'city', weight: 5 },
        { field: 'target_countries', weight: 10, isArray: true },
        { field: 'services', weight: 10, isArray: true },
        { field: 'specialization', weight: 10, isArray: true },
        { field: 'languages', weight: 10, isArray: true },
      ];

      requiredFields.forEach(({ field, weight, isArray, useField }) => {
        totalFields += weight;
        
        if (isArray) {
          let arrayData;
          try {
            arrayData = typeof data[field] === 'string' ? parseJSONField(data[field]) : data[field];
          } catch {
            arrayData = [];
          }
          
          if (Array.isArray(arrayData) && arrayData.length > 0) {
            filledFields += weight;
          }
        } else {
          const value = useField || data[field];
          if (value && value.toString().trim() !== '') {
            filledFields += weight;
          }
        }
      });

      const bonusFields = [
        'consultation_fee',
        'response_time',
        'availability',
        'comment'
      ];
      
      const bonusWeight = 1.25;
      bonusFields.forEach(field => {
        totalFields += bonusWeight;
        if (data[field]) {
          if (Array.isArray(data[field])) {
            if (data[field].length > 0) filledFields += bonusWeight;
          } else if (typeof data[field] === 'boolean') {
            filledFields += bonusWeight;
          } else if (data[field].toString().trim() !== '') {
            filledFields += bonusWeight;
          }
        }
      });

      const percentage = totalFields > 0 ? Math.round((filledFields / totalFields) * 100) : 0;
      return Math.min(100, percentage);
    };

    const completeness = calculateCompleteness(userData);
    const isComplete = completeness >= 100;
    
    // ✅ Build consultant_profile object
    let consultant_profile = null;
    
    if (userData.user_type === 'consultant') {
      consultant_profile = {
        profile_status: userData.profile_status || 'incomplete',
        is_pending: userData.profile_status === 'pending',
        is_approved: userData.profile_status === 'approved',
        is_eligible_for_approval: isComplete,
        completeness_percentage: completeness,
        profile_picture: userData.profile_picture,
        first_name: userData.first_name,
        last_name: userData.last_name,
        designation: userData.designation,
        phone: userData.consultant_phone || userData.phone,
        company_name: userData.company_name,
        address: userData.address,
        number_of_employees: userData.number_of_employees,
        nationality: userData.nationality,
        state: userData.state,
        city: userData.city,
        consultation_fee: parseFloat(userData.consultation_fee) || 0,
        target_countries: parseJSONField(userData.target_countries),
        services: parseJSONField(userData.services),
        specialization: parseJSONField(userData.specialization),
        languages: parseJSONField(userData.languages),
        response_time: userData.response_time || 'normal',
        digital_only: Boolean(userData.digital_only),
        availability: userData.availability || 'normal',
        comment: userData.comment,
        active_profile: userData.active_profile || '0',
        profile_completed_date: userData.profile_completed_date,
        approval_requested_date: userData.approval_requested_date,
        approved_date: userData.approved_date,
        rejection_reason: userData.rejection_reason
      };
    }

    const responseData = {
      id: userData.id,
      name: `${userData.first_name} ${userData.last_name}`,
      email: userData.email,
      role: userData.user_type,
      consultant_profile: consultant_profile
    };

    return NextResponse.json(
      {
        success: true,
        data: responseData
      },
      { status: 200 }
    );
  } catch (err) {
    console.error('check-auth error:', err);
    return NextResponse.json(
      { success: false, message: "Internal Server Error" },
      { status: 500 }
    );
  }
}