const ZARINPAL_MERCHANT = process.env.ZARINPAL_MERCHANT_ID ?? "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";
const IS_SANDBOX = process.env.NODE_ENV !== "production";

const BASE_URL = IS_SANDBOX
  ? "https://sandbox.zarinpal.com/pg/v4/payment"
  : "https://api.zarinpal.com/pg/v4/payment";

const GATEWAY = IS_SANDBOX
  ? "https://sandbox.zarinpal.com/pg/StartPay"
  : "https://www.zarinpal.com/pg/StartPay";

export async function requestPayment(amount: number, description: string, callbackUrl: string) {
  const res = await fetch(`${BASE_URL}/request.json`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      merchant_id: ZARINPAL_MERCHANT,
      amount, // تومان
      description,
      callback_url: callbackUrl,
    }),
  });

  const data = await res.json();

  if (data.data?.code === 100) {
    return {
      success: true,
      authority: data.data.authority as string,
      paymentUrl: `${GATEWAY}/${data.data.authority}`,
    };
  }

  return { success: false, error: data.errors?.message ?? "خطا در اتصال به درگاه" };
}

export async function verifyPayment(authority: string, amount: number) {
  const res = await fetch(`${BASE_URL}/verify.json`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      merchant_id: ZARINPAL_MERCHANT,
      amount,
      authority,
    }),
  });

  const data = await res.json();

  if (data.data?.code === 100 || data.data?.code === 101) {
    return { success: true, refId: String(data.data.ref_id) };
  }

  return { success: false, error: "پرداخت تایید نشد" };
}
