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';

// POST create complaint
export async function POST(req: NextRequest) {

      const commingHeaders = req.headers.get("authorization");

    if(commingHeaders !== 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 { name, subject, email, phone, message, location } = body;

    // Validation
    if (!email || !message) {
      return NextResponse.json(
        { success: false, error: "Email and message are required" },
        { status: 400 }
      );
    }

    console.log(JSON.stringify(body))

    const insertQuery = `
      INSERT INTO complaints (name, subject, email, phone, message, location)
      VALUES (?, ?, ?, ?, ?, ?)
    `;
    const [result] = await pool.query<ResultSetHeader>(insertQuery, [
      name,
      subject,
      email,
      phone || null,
      message,
      location || null,
    ]);

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

    const response = await fetch("https://crm-universitiespage.com/reactapis/api/website_complaints_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
        }
      )
    }

    if(phone !== "" && email !== "")
    {
      const [emailHash, phoneHash] = await Promise.all([
        hashData(email),
        hashData(phone)
      ]);

      const event = {
        event_name: "Complaints",
        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.COMPLAINTS, {
      email: email
    });

    if (result.affectedRows === 0) {
      return NextResponse.json(
        { success: false, message: "Failed to create complaint" },
        { status: 500 }
      );
    }

    return NextResponse.json(
      { success: true, message: "Complaint created successfully", id: result.insertId },
      { status: 201 }
    );
  } catch (error: any) {

    await connection.rollback();

    console.error("❌ POST /complaints error:", error);
    return NextResponse.json(
      { success: false, error: "Internal Server Error", details: error.message },
      { status: 500 }
    );
  }
}