interface PayPalCredentials {
  clientId: string;
  secret: string;
  isLive: boolean;
  baseUrl: string;
}

interface RawPaymentOption {
  name: string;
  visibility: string;
  is_live: string;
  key_1: string;
  key_2: string;
}

export async function getPayPalCredentials(): Promise<PayPalCredentials> {
  const apiBase =
    process.env.API_BASE_URL ??
    "https://stag.divinetechs.com/dttube/public/api/";
  const apiToken = process.env.NEXT_PUBLIC_API_TOKEN ?? "";

  const res = await fetch(`${apiBase}get_payment_option`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Accept: "application/json",
      "Api-Token": apiToken,
    },
    body: JSON.stringify({}),
    cache: "no-store",
  });

  if (!res.ok) {
    throw new Error(`Failed to fetch payment options: ${res.status}`);
  }

  const json = await res.json();
  const result: Record<string, RawPaymentOption> = json?.result ?? {};
  const paypal = result["paypal"];

  if (!paypal || paypal.visibility !== "1") {
    throw new Error("PayPal gateway is not enabled");
  }

  const clientId = paypal.key_1;
  const secret = paypal.key_2;

  if (!clientId || !secret) {
    throw new Error("PayPal credentials (key_1 / key_2) are not set in the admin panel");
  }

  const isLive = paypal.is_live === "1";
  const baseUrl = isLive
    ? "https://api-m.paypal.com"
    : "https://api-m.sandbox.paypal.com";

  return { clientId, secret, isLive, baseUrl };
}

export async function getPayPalAccessToken(creds: PayPalCredentials): Promise<string> {
  const encoded = Buffer.from(`${creds.clientId}:${creds.secret}`).toString("base64");

  const res = await fetch(`${creds.baseUrl}/v1/oauth2/token`, {
    method: "POST",
    headers: {
      Authorization: `Basic ${encoded}`,
      "Content-Type": "application/x-www-form-urlencoded",
    },
    body: "grant_type=client_credentials",
  });

  if (!res.ok) {
    const err = await res.text();
    throw new Error(`PayPal auth failed (${res.status}): ${err}`);
  }

  const data = await res.json();
  return data.access_token as string;
}
