import type {
  DepositIntent,
  DepositIntentInput,
  PaymentProvider,
  WithdrawalInput
} from "@/server/providers/payment/types";

export class HttpPaymentProvider implements PaymentProvider {
  constructor(
    public readonly key: string,
    private readonly baseUrl: string,
    private readonly apiKey: string
  ) {}

  createDepositIntent(input: DepositIntentInput): Promise<DepositIntent> {
    return this.request("/deposit-intents", input);
  }

  requestWithdrawal(input: WithdrawalInput): Promise<{ providerRef: string; status: "PENDING" }> {
    return this.request("/withdrawals", input);
  }

  async healthCheck() {
    const started = Date.now();
    await this.request("/health", {});
    return { ok: true, latencyMs: Date.now() - started };
  }

  private async request<T>(path: string, body: unknown): Promise<T> {
    const response = await fetch(new URL(path, this.baseUrl), {
      method: "POST",
      headers: {
        authorization: `Bearer ${this.apiKey}`,
        "content-type": "application/json",
        accept: "application/json"
      },
      body: JSON.stringify(body),
      cache: "no-store"
    });

    if (!response.ok) {
      throw new Error(`Payment provider request failed: ${response.status}`);
    }

    return response.json() as Promise<T>;
  }
}
