import { openStore } from "@/lib/data/store";
import type { GatewaySettings } from "@/lib/types";

/**
 * Pays someone out through PayPal.
 *
 * Only used when an admin marks a withdrawal paid and PayPal payouts are
 * switched on; otherwise paying out stays a manual step, which is how most
 * small sites work.
 */
export async function payoutViaPayPal(opts: {
  email: string;
  amount: number;
  currency: string;
  note?: string;
}): Promise<{ sent: boolean; reason?: string; batchId?: string }> {
  const store = await openStore();
  const s = await store.settings();
  const gateways = await store.small<GatewaySettings>("gateways", {} as GatewaySettings);

  if (s.paypalPayoutsEnabled !== true) {
    return { sent: false, reason: "PayPal payouts are turned off" };
  }

  const g = gateways.paypal;
  if (!g.clientId || !g.clientSecret) {
    return { sent: false, reason: "PayPal isn't configured" };
  }

  const base = g.sandbox
    ? "https://api-m.sandbox.paypal.com"
    : "https://api-m.paypal.com";

  try {
    // A token first — PayPal's payouts API is separate from checkout.
    const auth = await fetch(`${base}/v1/oauth2/token`, {
      method: "POST",
      headers: {
        Authorization: `Basic ${Buffer.from(`${g.clientId}:${g.clientSecret}`).toString("base64")}`,
        "Content-Type": "application/x-www-form-urlencoded",
      },
      body: "grant_type=client_credentials",
    });

    if (!auth.ok) return { sent: false, reason: "PayPal wouldn't authenticate" };
    const { access_token } = await auth.json();

    const res = await fetch(`${base}/v1/payments/payouts`, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${access_token}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        sender_batch_header: {
          // Unique per payout, so a retry can't pay twice.
          sender_batch_id: `payout_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
          email_subject: "You've been paid",
        },
        items: [
          {
            recipient_type: "EMAIL",
            amount: { value: opts.amount.toFixed(2), currency: opts.currency },
            receiver: opts.email,
            note: opts.note ?? "Withdrawal",
          },
        ],
      }),
    });

    if (!res.ok) {
      const detail = await res.json().catch(() => null);
      return { sent: false, reason: detail?.message ?? "PayPal refused the payout" };
    }

    const data = await res.json();
    return { sent: true, batchId: data?.batch_header?.payout_batch_id };
  } catch {
    return { sent: false, reason: "Couldn't reach PayPal" };
  }
}
