import type { KycApplicantInput, KycProvider } from "@/server/providers/kyc/types";

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

  createApplicant(input: KycApplicantInput): Promise<{ providerRef: string; status: "PENDING" }> {
    return this.request("/applicants", input);
  }

  screenApplicant(input: KycApplicantInput): Promise<{
    amlScore: number;
    pepMatch: boolean;
    sanctionsMatch: boolean;
    countryRisk: string;
  }> {
    return this.request("/screenings", 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(`KYC provider request failed: ${response.status}`);
    }

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