import {
  createAdminClient,
} from "../supabase/admin";

import {
  processWhatsAppNotification,
} from "../notifications/processNotification";


type PaystackVerifyResponse = {
  status: boolean;

  message: string;

  data?: {
    status: string;

    reference: string;

    amount:
      | number
      | string;

    requested_amount:
      | number
      | string;

    currency: string;

    paid_at:
      | string
      | null;
  };
};


export type VerifiedOrder = {
  id: string;

  orderNumber: string;

  customerName: string;

  total: number;

  paymentStatus: string;
};


export type VerificationResult = {
  success: boolean;

  message: string;

  order?: VerifiedOrder;
};


export async function verifyPaystackPayment(
  reference: string
): Promise<VerificationResult> {
  try {
    // =====================================================
    // CLEAN REFERENCE
    // =====================================================

    const cleanReference =
      reference.trim();


    if (!cleanReference) {
      return {
        success: false,

        message:
          "Payment reference is missing.",
      };
    }


    // =====================================================
    // PAYSTACK CONFIGURATION
    // =====================================================

    const paystackSecretKey =
      process.env.PAYSTACK_SECRET_KEY;


    if (!paystackSecretKey) {
      console.error(
        "PAYSTACK_SECRET_KEY is missing."
      );


      return {
        success: false,

        message:
          "Payment verification is not configured.",
      };
    }


    const supabase =
      createAdminClient();


    // =====================================================
    // FIND PAYMENT RECORD
    // =====================================================

    const {
      data: payment,
      error: paymentError,
    } =
      await supabase
        .from("payments")
        .select(
          `
            id,
            order_id,
            reference,
            amount,
            currency,
            status,
            paid_at
          `
        )
        .eq(
          "reference",
          cleanReference
        )
        .maybeSingle();


    if (paymentError) {
  console.error(
    "Payment lookup error:",
    paymentError
  );

  return {
    success: false,
    message:
      "We could not verify this payment at the moment.",
  };
}


if (!payment) {
  return {
    success: false,
    message:
      "This payment reference is not associated with a PELCY order.",
  };
}


    // =====================================================
    // FIND ORDER
    // =====================================================

    const {
      data: order,
      error: orderError,
    } =
      await supabase
        .from("orders")
        .select(
          `
            id,
            order_number,
            customer_name,
            total,
            payment_status,
            paystack_reference
          `
        )
        .eq(
          "id",
          payment.order_id
        )
        .maybeSingle();


    if (
      orderError ||
      !order
    ) {
      console.error(
        "Order lookup error:",
        orderError
      );


      return {
        success: false,

        message:
          "The related PELCY order could not be found.",
      };
    }


    // =====================================================
    // REFERENCE MUST MATCH ORDER
    // =====================================================

    if (
      order.paystack_reference !==
      cleanReference
    ) {
      return {
        success: false,

        message:
          "Payment reference does not match this order.",
      };
    }


    // =====================================================
    // VERIFY WITH PAYSTACK
    // =====================================================

    const response =
      await fetch(
        `https://api.paystack.co/transaction/verify/${encodeURIComponent(
          cleanReference
        )}`,
        {
          method:
            "GET",

          headers: {
            Authorization:
              `Bearer ${paystackSecretKey}`,
          },

          cache:
            "no-store",
        }
      );


    const result =
      (await response.json()) as
        PaystackVerifyResponse;


    if (
      !response.ok ||
      !result.status ||
      !result.data
    ) {
      console.error(
        "Paystack verification error:",
        result
      );


      return {
        success: false,

        message:
          result.message ||
          "Paystack could not verify this payment.",
      };
    }


    // =====================================================
    // PAYMENT MUST BE SUCCESSFUL
    // =====================================================

    if (
      result.data.status !==
      "success"
    ) {
      return {
        success: false,

        message:
          `Payment status is ${result.data.status}.`,
      };
    }


    // =====================================================
    // REFERENCE MUST MATCH PAYSTACK
    // =====================================================

    if (
      result.data.reference !==
      cleanReference
    ) {
      return {
        success: false,

        message:
          "Paystack returned a different payment reference.",
      };
    }


    // =====================================================
    // CURRENCY MUST BE NGN
    // =====================================================

    if (
      result.data.currency !==
      "NGN"
    ) {
      return {
        success: false,

        message:
          "Unexpected payment currency.",
      };
    }


    // =====================================================
    // VERIFY PAYMENT AMOUNT
    //
    // Paystack uses kobo.
    // We compare requested_amount with the PELCY
    // order total converted to kobo.
    // =====================================================

    const expectedAmountInKobo =
      Math.round(
        Number(
          order.total
        ) * 100
      );


    const requestedAmountInKobo =
      Number(
        result.data.requested_amount
      );


    if (
      !Number.isFinite(
        requestedAmountInKobo
      )
    ) {
      console.error(
        "Paystack requested amount is invalid:",
        result.data.requested_amount
      );


      return {
        success: false,

        message:
          "Paystack returned an invalid requested amount.",
      };
    }


    if (
      requestedAmountInKobo !==
      expectedAmountInKobo
    ) {
      console.error(
        "Payment requested amount mismatch:",
        {
          expected:
            expectedAmountInKobo,

          requested:
            requestedAmountInKobo,

          charged:
            Number(
              result.data.amount
            ),
        }
      );


      return {
        success: false,

        message:
          "Payment amount does not match the order total.",
      };
    }


    // =====================================================
    // MARK PAYMENT + ORDER AS PAID
    // =====================================================

    const {
      data: confirmedOrder,
      error: updateError,
    } =
      await supabase.rpc(
        "mark_pelcy_payment_success",
        {
          p_reference:
            cleanReference,

          p_paid_at:
            result.data.paid_at,
        }
      );


    if (updateError) {
      console.error(
        "Payment confirmation database error:",
        updateError
      );


      return {
        success: false,

        message:
          "Payment was verified but the order could not be updated.",
      };
    }


    if (
      !confirmedOrder ||
      !confirmedOrder.id
    ) {
      console.error(
        "Payment confirmation returned no order:",
        confirmedOrder
      );


      return {
        success: false,

        message:
          "Payment was verified but the confirmed order could not be loaded.",
      };
    }


    // =====================================================
    // AUTOMATIC PAYMENT VERIFIED WHATSAPP NOTIFICATION
    // =====================================================
    //
    // IMPORTANT:
    // Payment verification has already succeeded BEFORE
    // this section executes.
    //
    // Therefore, a WhatsApp problem must NEVER cause the
    // customer's successful payment to become unsuccessful.
    // =====================================================

    try {
      const {
        data:
          notificationEvent,
        error:
          notificationEventError,
      } =
        await supabase
          .from(
            "notification_events"
          )
          .select(
            "id, status"
          )
          .eq(
            "order_id",
            confirmedOrder.id
          )
          .eq(
            "event_type",
            "payment_verified"
          )
          .eq(
            "channel",
            "whatsapp"
          )
          .maybeSingle();


      if (
        notificationEventError
      ) {
        console.error(
          "Could not find payment_verified notification event:",
          notificationEventError
        );
      } else if (
        notificationEvent
      ) {
        const notificationResult =
          await processWhatsAppNotification(
            notificationEvent.id
          );


        console.log(
          "Automatic payment-verified WhatsApp notification result:",
          notificationResult
        );
      } else {
        console.warn(
          "No payment_verified WhatsApp notification event was found for order:",
          confirmedOrder.id
        );
      }
    } catch (
      notificationError
    ) {
      // ===================================================
      // DO NOT FAIL THE CUSTOMER'S PAYMENT
      // ===================================================

      console.error(
        "Automatic payment-verified WhatsApp notification failed:",
        notificationError
      );
    }


    // =====================================================
    // SUCCESS
    // =====================================================

    return {
      success: true,

      message:
        "Payment verified successfully.",

      order: {
        id:
          confirmedOrder.id,

        orderNumber:
          confirmedOrder.orderNumber,

        customerName:
          confirmedOrder.customerName,

        total:
          Number(
            confirmedOrder.total
          ),

        paymentStatus:
          confirmedOrder.paymentStatus,
      },
    };

  } catch (error) {
    console.error(
      "PELCY payment verification error:",
      error
    );


    return {
      success: false,

      message:
        "Something went wrong while verifying payment.",
    };
  }
}