import { randomUUID } from "crypto";
import { NextResponse } from "next/server";

import {
  createAdminClient,
} from "../../../lib/supabase/admin";

import {
  processWhatsAppNotification,
} from "../../../lib/notifications/processNotification";


type CartItem = {
  productId?: unknown;
  variantId?: unknown;
  quantity?: unknown;
};


type CheckoutBody = {
  customerName?: unknown;
  customerEmail?: unknown;
  customerPhone?: unknown;
  customerWhatsapp?: unknown;

  deliveryZoneId?: unknown;
  deliveryAddress?: unknown;
  deliveryNotes?: unknown;

  items?: unknown;
};


function cleanText(
  value: unknown,
  maxLength = 500
) {
  if (
    typeof value !==
    "string"
  ) {
    return "";
  }

  return value
    .trim()
    .slice(
      0,
      maxLength
    );
}


function createOrderNumber() {
  const now =
    new Date();

  const year =
    now.getFullYear();

  const month =
    String(
      now.getMonth() + 1
    ).padStart(
      2,
      "0"
    );

  const day =
    String(
      now.getDate()
    ).padStart(
      2,
      "0"
    );

  const randomPart =
    randomUUID()
      .replaceAll(
        "-",
        ""
      )
      .slice(
        0,
        12
      )
      .toUpperCase();

  return `PEL-${year}${month}${day}-${randomPart}`;
}


export async function POST(
  request: Request
) {
  try {
    // =====================================================
    // READ REQUEST
    // =====================================================

    const body =
      (await request.json()) as
        CheckoutBody;


    const customerName =
      cleanText(
        body.customerName,
        150
      );


    const customerEmail =
      cleanText(
        body.customerEmail,
        200
      );


    const customerPhone =
      cleanText(
        body.customerPhone,
        50
      );


    const customerWhatsapp =
      cleanText(
        body.customerWhatsapp,
        50
      );


    const deliveryZoneId =
      cleanText(
        body.deliveryZoneId,
        100
      );


    const deliveryAddress =
      cleanText(
        body.deliveryAddress,
        500
      );


    const deliveryNotes =
      cleanText(
        body.deliveryNotes,
        1000
      );


    // =====================================================
    // BASIC VALIDATION
    // =====================================================

    if (!customerName) {
      return NextResponse.json(
        {
          error:
            "Customer name is required.",
        },
        {
          status: 400,
        }
      );
    }


    if (!customerPhone) {
      return NextResponse.json(
        {
          error:
            "Phone number is required.",
        },
        {
          status: 400,
        }
      );
    }


    if (!customerEmail) {
      return NextResponse.json(
        {
          error:
            "Email address is required for payment.",
        },
        {
          status: 400,
        }
      );
    }


    if (!deliveryZoneId) {
      return NextResponse.json(
        {
          error:
            "Please select a delivery area.",
        },
        {
          status: 400,
        }
      );
    }


    if (!deliveryAddress) {
      return NextResponse.json(
        {
          error:
            "Delivery address is required.",
        },
        {
          status: 400,
        }
      );
    }


    if (
      !Array.isArray(
        body.items
      ) ||
      body.items.length ===
        0
    ) {
      return NextResponse.json(
        {
          error:
            "Your cart is empty.",
        },
        {
          status: 400,
        }
      );
    }


    if (
      body.items.length >
      50
    ) {
      return NextResponse.json(
        {
          error:
            "Too many products in the cart.",
        },
        {
          status: 400,
        }
      );
    }


    // =====================================================
    // PREPARE CART
    // =====================================================

    const items =
      (
        body.items as
          CartItem[]
      ).map(
        (item) => ({
          productId:
            cleanText(
              item.productId,
              100
            ),

          variantId:
            item.variantId ===
              null
              ? null
              : cleanText(
                  item.variantId,
                  100
                ) ||
                null,

          quantity:
            Number(
              item.quantity
            ),
        })
      );


    for (
      const item of items
    ) {
      if (
        !item.productId ||
        !Number.isInteger(
          item.quantity
        ) ||
        item.quantity < 1 ||
        item.quantity > 100
      ) {
        return NextResponse.json(
          {
            error:
              "One of the cart items is invalid.",
          },
          {
            status: 400,
          }
        );
      }
    }


    // =====================================================
    // CREATE ATOMIC ORDER
    // =====================================================

    const supabase =
      createAdminClient();


    const orderNumber =
      createOrderNumber();


    const {
      data,
      error,
    } =
      await supabase.rpc(
        "create_pelcy_order_atomic",
        {
          p_order_number:
            orderNumber,

          p_customer_name:
            customerName,

          p_customer_email:
            customerEmail,

          p_customer_phone:
            customerPhone,

          p_customer_whatsapp:
            customerWhatsapp ||
            null,

          p_delivery_zone_id:
            deliveryZoneId,

          p_delivery_address:
            deliveryAddress,

          p_delivery_notes:
            deliveryNotes ||
            null,

          p_items:
            items,
        }
      );


    // =====================================================
    // HANDLE ORDER CREATION ERROR
    // =====================================================

    if (error) {
      console.error(
        "Atomic order error:",
        error
      );


      let message =
        "Could not create your order.";


      if (
        error.message.includes(
          "DELIVERY_ZONE_NOT_AVAILABLE"
        )
      ) {
        message =
          "The selected delivery area is no longer available.";
      } else if (
        error.message.includes(
          "PRODUCT_NOT_AVAILABLE"
        )
      ) {
        message =
          "One of the products in your cart is no longer available.";
      } else if (
        error.message.includes(
          "VARIANT_NOT_AVAILABLE"
        )
      ) {
        message =
          "One of the selected product sizes is no longer available.";
      } else if (
        error.message.includes(
          "INVALID_QUANTITY"
        )
      ) {
        message =
          "One of the product quantities is invalid.";
      }


      return NextResponse.json(
        {
          error:
            message,
        },
        {
          status: 400,
        }
      );
    }


    // =====================================================
    // AUTOMATIC NEW ORDER WHATSAPP NOTIFICATION
    // =====================================================
    //
    // IMPORTANT:
    // The order has already been successfully created
    // before this section runs.
    //
    // Therefore, if WhatsApp fails for any reason,
    // the customer's order will NOT be cancelled or lost.
    // =====================================================

    try {
      // ---------------------------------------------------
      // FIND THE ORDER THAT WAS JUST CREATED
      // ---------------------------------------------------

      const {
        data: createdOrder,
        error: createdOrderError,
      } =
        await supabase
          .from("orders")
          .select("id")
          .eq(
            "order_number",
            orderNumber
          )
          .single();


      if (
        createdOrderError ||
        !createdOrder
      ) {
        console.error(
          "Could not find newly created order for WhatsApp notification:",
          createdOrderError
        );
      } else {
        // -------------------------------------------------
        // FIND THE NOTIFICATION EVENT
        // -------------------------------------------------
        //
        // Our Supabase trigger automatically creates
        // this row when the order is inserted.
        // -------------------------------------------------

        const {
          data:
            notificationEvent,
          error:
            notificationEventError,
        } =
          await supabase
            .from(
              "notification_events"
            )
            .select(
              "id, status"
            )
            .eq(
              "order_id",
              createdOrder.id
            )
            .eq(
              "event_type",
              "order_created"
            )
            .eq(
              "channel",
              "whatsapp"
            )
            .maybeSingle();


        if (
          notificationEventError
        ) {
          console.error(
            "Could not find new-order notification event:",
            notificationEventError
          );
        } else if (
          notificationEvent
        ) {
          // -----------------------------------------------
          // PROCESS THE WHATSAPP NOTIFICATION
          // -----------------------------------------------

          const notificationResult =
            await processWhatsAppNotification(
              notificationEvent.id
            );


          console.log(
            "Automatic new-order WhatsApp notification result:",
            notificationResult
          );
        } else {
          console.warn(
            "No order_created WhatsApp notification event was found for:",
            orderNumber
          );
        }
      }
    } catch (
      notificationError
    ) {
      // ---------------------------------------------------
      // DO NOT FAIL THE CUSTOMER'S ORDER
      // ---------------------------------------------------

      console.error(
        "Automatic new-order WhatsApp notification failed:",
        notificationError
      );
    }


    // =====================================================
    // SUCCESS
    // =====================================================

    return NextResponse.json(
      {
        success: true,

        order:
          data,
      },
      {
        status: 201,
      }
    );

  } catch (error) {
    console.error(
      "PELCY order API error:",
      error
    );


    return NextResponse.json(
      {
        error:
          "Something went wrong while creating your order.",
      },
      {
        status: 500,
      }
    );
  }
}