import pool from '../../../../lib/db/db';
import { NextRequest, NextResponse } from 'next/server';
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();

    const { office_location, user_name, user_email, phone_number, message } = body;

    if (!office_location || !user_name || !user_email || !phone_number || !message) {
      return NextResponse.json(
        { success: false, message: 'All fields are required' },
        { status: 400 }
      );
    }

    const [result] = await pool.query<ResultSetHeader>(
      `INSERT INTO contact_us_messages 
        (office_location, user_name, user_email, phone_number, message) 
       VALUES (?, ?, ?, ?, ?)`,
      [office_location, user_name, user_email, phone_number, message]
    );

    if (result.affectedRows === 0) {
      return NextResponse.json(
        { success: false, message: 'Failed to save contact message' },
        { status: 500 }
      );
    }

    const crmPayload = {
  ...body,
  lead_type: 'mobile'
};

    const response = await fetch("https://crm-universitiespage.com/reactapis/api/website_contact_us_crm/store", {
      method: "POST",
      body: JSON.stringify(crmPayload),
      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
        }
      )
    }

    const [emailHash, phoneHash] = await Promise.all([
      hashData(user_email),
      hashData(phone_number)
    ]);

    const event = {
      event_name: "Contact Us",
      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) {
      return NextResponse.json(
        {
          message: "Failed to store the Event.",
          success: false
        },
        {
          status: 500
        }
      )
    }

    await connection.commit();

    await sendFormEmail(FormType.CONTACT_US, {
      email: user_email
    });


    return NextResponse.json(
      { success: true, message: 'Message submitted successfully' },
      { status: 201 }
    );
  } catch (error: any) {

    await connection.rollback();

    console.error("❌ POST /contactUs error:", error);
    return NextResponse.json(
      { success: false, message: 'Internal server error' },
      { status: 500 }
    );
  }
}
