import { runtimeEnv } from "./platform";

type LloydResponse = {
  status?: string;
  message?: string;
  data?: Record<string, unknown>;
  transaction?: Record<string, unknown>;
};

async function request(path: string, body: Record<string, unknown>): Promise<LloydResponse> {
  const runtime = runtimeEnv();
  if (!runtime.LLOYD_API_KEY) throw new Error("Lloyd API is not configured.");
  const base = (runtime.LLOYD_API_BASE_URL || "https://api.sonicpesa.com/api/v1").replace(/\/$/, "");
  const response = await fetch(`${base}${path}`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-API-KEY": runtime.LLOYD_API_KEY,
      ...(runtime.LLOYD_API_SECRET ? { "X-API-SECRET": runtime.LLOYD_API_SECRET } : {}),
    },
    body: JSON.stringify(body),
  });
  const payload = await response.json().catch(() => ({})) as LloydResponse;
  if (!response.ok || payload.status === "error") {
    throw new Error(payload.message || `Payment service returned ${response.status}.`);
  }
  return payload;
}

export function createOrder(phone: string, amount: number) {
  return request("/payment/create_order", {
    buyer_email: "customer@loyd.local",
    buyer_name: "Loyd Customer",
    buyer_phone: phone,
    amount,
    currency: "TZS",
  });
}

export function getOrderStatus(orderId: string) {
  return request("/payment/order_status", { order_id: orderId });
}

export function normalizeTanzaniaPhone(input: string) {
  const digits = input.replace(/\D/g, "");
  if (/^255\d{9}$/.test(digits)) return digits;
  if (/^0\d{9}$/.test(digits)) return `255${digits.slice(1)}`;
  if (/^\d{9}$/.test(digits)) return `255${digits}`;
  throw new Error("Weka namba sahihi ya Tanzania, mfano 0712345678.");
}
