import pool from '../../../../lib/db/db';
import type { ResultSetHeader } from 'mysql2';
import { sendFormEmail, FormType } from '../../../../lib/mailer';
import { hashData } from '../../../../lib/hashData';
import { DiscountOfferSchema } from '../../../../validations/discount-offer';
import { NextRequest, NextResponse } from 'next/server';

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();

  try {
    await connection.beginTransaction();

    const accessToken = process.env.FACEBOOK_ACCESS_CODE;
    const pixelId = process.env.FACEBOOK_PIXEL_ID;

    const body = await req.json();
    
    // Transform frontend field names to match Zod schema
    const transformedBody = {
      name: body.name,
      email: body.email,
      phone_number: body.phone, // Transform 'phone' to 'phone_number'
      phonecode: body.phonecode,
      last_education: body.lastEducation, // Transform 'lastEducation' to 'last_education'
      last_education_per: body.lastEducationPer, // Transform 'lastEducationPer' to 'last_education_per'
      office_location: body.location, // Transform 'location' to 'office_location'
      family_detail: body.familyDetail // Transform 'familyDetail' to 'family_detail'
    };

    // Validate with Zod schema
    let parsed;
    try {
      parsed = DiscountOfferSchema.parse(transformedBody);
    } catch (validationError: any) {
      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,
      last_education_per,
      office_location,
      family_detail
    } = parsed;

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

    // Insert into database (using original field names for database)
    const [insertResult] = await connection.query<ResultSetHeader>(
      `INSERT INTO discountOffers 
      (name, email, phone, lastEducation, lastEducationPer, location, familyDetail, city) 
      VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
      [name, email, phoneWithCode, last_education, last_education_per, office_location, family_detail, office_location]
    );

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

    // Prepare payload for CRM (using original field names for CRM)
    const crmPayload = {
      name,
      email,
      phone: phoneWithCode,
      lastEducation: last_education,
      lastEducationPer: last_education_per,
      location: office_location,
      lead_type: 'mobile',
      familyDetail: family_detail
    };

    // console.log(JSON.stringify(crmPayload))

    const response = await fetch("https://crm-universitiespage.com/reactapis/api/website_discount_offer_crm/store?location=lahore", {
      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
        }
      );
    }

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

    const event = {
      event_name: "Discount Offer",
      event_time: Math.floor(Date.now() / 1000),
      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.DISCOUNT_OFFER, {
        email: email
      });
    }

    return NextResponse.json(
      { success: true, message: 'Discount offer created successfully' },
      { status: 200 }
    );
  } catch (error: any) {
    await connection.rollback();

    console.error('DiscountOffers POST 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: error.message },
      { status: 500 }
    );
  } finally {
    connection.release();
  }
}