import pool from '../../../../lib/db/db';
import { NextRequest, NextResponse } from 'next/server';
import { FreeConsultationSchemaSoft as Schema } from '../../../../validations/freeconsultation';
import { ResultSetHeader, RowDataPacket } from 'mysql2';
import { sendFormEmail, FormType } from '../../../../lib/mailer';
import { hashData } from '../../../../lib/hashData';

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

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

  const connection = await pool.getConnection(); // Start a new connection

  try {
    await connection.beginTransaction(); // Start a transaction

    const accessToken = process.env.FACEBOOK_ACCESS_CODE; // your FB access token
    const pixelId = process.env.FACEBOOK_PIXEL_ID;

    const body = await req.json();
    
    // Validate with Zod schema
    let parsed;
    try {
      parsed = Schema.parse(body);
    } catch (validationError: any) {
      // Format Zod errors for frontend display
      const formattedErrors = validationError.errors.map((error: any) => ({
        field: error.path.join('.'),
        message: error.message
      }));
      
      return NextResponse.json({ 
        success: false, 
        message: 'Validation failed. Please check your input.',
        errors: formattedErrors
      }, { status: 400 });
    }

    const { name, email, phone_number, phonecode, last_education, interested_country, apply_for, office_to_visit } = parsed;

    const phonewithcode = `${phonecode}${phone_number}`;

    const [getCountryName] = await connection.query<RowDataPacket[]>("SELECT name FROM countries_with_phone WHERE phonecode = ?", [phonecode])

    if(getCountryName.length === 0)
    {
      return NextResponse.json(
        {
          success: false,
          message: 'Invalid country code'
        },
        {
          status: 500
        }
      )
    }
    // Insert into database with new field names
    const [newApplication] = await connection.query<ResultSetHeader>(
      `INSERT INTO online_consultants (
        application_type, 
        student_name, 
        student_email, 
        student_phone_number, 
        student_last_education, 
        student_apply_for, 
        interested_country, 
        office_to_visit, 
        student_country,
        student_city,
        choosable_status, 
        created_at, 
        updated_at
      ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'Pending', NOW(), NOW())`,
      [
        '2', // application_type
        name, // student_name
        email || '', // student_email
        phonewithcode, // student_phone_number
        last_education, // student_last_education
        apply_for, // student_apply_for
        interested_country, // interested_country
        office_to_visit, // office_to_visit
        getCountryName[0].name, // student_country
        office_to_visit // student_city
      ]
    );

    if (newApplication.affectedRows === 0) {
      return NextResponse.json({ 
        success: false, 
        message: 'Failed to create application' 
      }, { status: 500 });
    }

    // Prepare payload for CRM
    const payloadData = {
      application_type: "2",
      student_name: name,
      student_email: email || '',
      student_phone_number: phonewithcode,
      student_country: getCountryName[0].name,
      student_city: office_to_visit,
      student_last_education: last_education,
      student_apply_for: apply_for,
      interested_country: interested_country,
      office_to_visit: office_to_visit,
      choosable_status: "Pending",
      lead_type: "mobile"
    };

    // Send to CRM
    const response = await fetch("https://crm-universitiespage.com/reactapis/api/website_online_consultation_crm/store?location=lahore", {
      method: "POST",
      body: JSON.stringify(payloadData),
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `${process.env.CRM_API_KEY}`,
      },
    });

    const data = await response.json();

    if (data?.status_code !== 200) {
      await connection.rollback();
      return NextResponse.json(
        {
          message: "Failed to submit your form. Please try again later.",
          success: false
        },
        {
          status: 500
        }
      );
    }

    // Facebook Pixel Event
    const [emailHash, phoneHash] = await Promise.all([
      email ? hashData(email) : Promise.resolve(''),
      hashData(phonewithcode)
    ]);

    const event = {
      event_name: "Apply Online",
      event_time: Math.floor(Date.now() / 1000), // UNIX timestamp
      user_data: {
        email: emailHash,
        ph: phoneHash,
      },
    };

    const payload = { data: [event] };

    const fbResponse = await fetch(
      `https://graph.facebook.com/v14.0/${pixelId}/events?access_token=${accessToken}`,
      {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      }
    );

    if (!fbResponse.ok) {
      console.error("Facebook Pixel event failed:", await fbResponse.text());
      // Don't fail the entire request if Facebook Pixel fails
    }

    await connection.commit();

    // Send confirmation email if email is provided
    if (email) {
      await sendFormEmail(FormType.APPLY_ONLINE, {
        email: email
      });
    }

    return NextResponse.json({ 
      success: true, 
      message: 'Application created successfully' 
    }, { status: 201 });

  } catch (error: any) {
    await connection.rollback();
    
    console.error("POST online_consultants error:", error);
    
    // Handle Zod validation errors
    if (error.name === 'ZodError') {
      const formattedErrors = error.errors.map((err: any) => ({
        field: err.path.join('.'),
        message: err.message
      }));
      
      return NextResponse.json({ 
        success: false, 
        message: 'Validation failed. Please check your input.',
        errors: formattedErrors
      }, { status: 400 });
    }
    
    return NextResponse.json({ 
      success: false, 
      message: 'Internal server error', 
      error: process.env.NODE_ENV === 'development' ? error.message : null 
    }, { status: 500 });
  } finally {
    connection.release(); // Always release the connection
  }
}