import pool from "../../../../lib/db/db";
import { NextResponse } from "next/server";
import type { RowDataPacket } from "mysql2";


// ------------------ POST new subscriber ------------------
export async function POST(req: Request) {

  const connection = await pool.getConnection();
  
  try {
    let body: any;
    try {
      body = await req.json();
    } catch {
      return NextResponse.json(
        { success: false, error: "Invalid or missing JSON body" },
        { status: 400 }
      );
    }

    if (!body.email) {
      return NextResponse.json(
        { success: false, error: "Email is required" },
        { status: 400 }
      );
    }

    await connection.beginTransaction();

    // Insert new subscriber
    const [result] = await pool.execute(
      `INSERT INTO subscribers (email, created_at, updated_at) VALUES (?, ?, ?)`,
      [body.email, new Date(), new Date()]
    );

    const insertId = (result as any).insertId;

    const crmPayload = {
      "email": body.email
    };

    // Send to CRM API
    let crmResponse;
    try {
      crmResponse = await fetch(
        "https://crm-universitiespage.com/reactapis/api/store-subscribe",
        {
          method: "POST",
          body: JSON.stringify(crmPayload),
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `${process.env.CRM_API_KEY}`,
          },
        }
      );

      if (!crmResponse.ok) {
        throw new Error(`CRM API responded with status: ${crmResponse.status}`);
      }

      const crmData = await crmResponse.json();

      if (crmData?.status_code !== 200) {
        throw new Error('CRM API returned non-success status');
      }

    } catch (crmError) {
      await connection.rollback();
      console.error('CRM API Error:', crmError);
      
      return NextResponse.json(
        {
          success: false,
          message: "Failed to submit your form to CRM. Please try again later."
        },
        { status: 502 } // Bad Gateway
      );
    }

    await connection.commit();

    // Fetch newly inserted subscriber
    const [rows] = await pool.query<RowDataPacket[]>(
      `SELECT * FROM subscribers WHERE id = ?`,
      [insertId]
    );

    return NextResponse.json({ success: true, data: rows[0] });
  } catch (error: any) {
    await connection.rollback();
    console.error("Error creating subscriber:", error);
    return NextResponse.json(
      { success: false, error: error.message },
      { status: 500 }
    );
  } finally {
    connection.release();
  }
}
