import { paymentHelpers } from "$helpers/index.js";

export const CONFIRM = async (req, res) => {
  try {
    const payment = await paymentHelpers.startPayment({
      body: req.body,
      params: req.params,
      user: req.user,
      req,
    });

    if (req.body.redirect === true) {
      return res.redirect(303, payment.redirectUrl);
    }

    return res.status(201).send(payment);
  } catch (error) {
    const status = error.status || 500;
    const response = {
      message: error.message || "Payment confirmation failed.",
    };

    if (error.gatewayStatus !== undefined) {
      response.gatewayStatus = error.gatewayStatus;
    }

    return res.status(status).send(response);
  }
};

export const PARSIAN_CALLBACK = async (req, res) => {
  try {
    const result = await paymentHelpers.handleParsianCallback(req.body);
    return paymentHelpers.finishCallback(req, res, result);
  } catch (error) {
    console.error("Payment Parsian callback failed:", error);
    return paymentHelpers.finishCallback(req, res, { status: "failed" });
  }
};

export const RECEIPT = async (req, res) => {
  try {
    const receipt = await paymentHelpers.getReceipt({
      orderId: String(req.params.orderId || "").trim(),
      receiptToken: String(req.query.receiptToken || req.query.rt || ""),
    });

    return paymentHelpers.noStore(res).status(200).send(receipt);
  } catch (error) {
    const status = error.status || 500;
    const message =
      status === 500
        ? error.message || "Receipt lookup failed."
        : error.message ||
          (status === 400
            ? "Invalid receipt request."
            : "Receipt is not available.");

    return paymentHelpers
      .noStore(res)
      .status(status)
      .send({
        success: false,
        title: "Transaction status",
        message,
      });
  }
};

export const CHECK_SEPAH_PAYMENT = async (req, res) => {
  try {
    const result = await paymentHelpers.confirmSepahPayment({
      requestId: String(req.params.requestId || "").trim(),
      user: req.user,
    });

    return paymentHelpers.noStore(res).status(200).send(result);
  } catch (error) {
    return paymentHelpers.noStore(res).status(error.status || 500).send({
      succeeded: false,
      message: error.message || "Sepah payment confirmation failed.",
    });
  }
};
