/**
 * ClaimDesk (claimdesk.ng) — Zero-Dependency TypeScript Client & HMAC Webhook Verifier
 * Drop this file directly into Node.js (18+), Next.js, Cloudflare Workers, Bun, or Deno.
 *
 * Quickstart:
 *   const claimdesk = new ClaimDeskClient({
 *     apiKey: process.env.CLAIMDESK_API_KEY!, // cd_live_...
 *     orgId: process.env.CLAIMDESK_ORG_ID || 'YOUR_ORG_UUID',
 *     baseUrl: 'https://api.claimdesk.ng',
 *   });
 */

export const DEFAULT_CLAIMDESK_BASE_URL = 'https://api.claimdesk.ng';

export interface ClaimDeskClientOptions {
  apiKey: string;
  orgId: string;
  baseUrl?: string;
  actingHospitalOrgId?: string;
}

export interface ClaimDeskRequestOptions {
  method?: 'GET' | 'POST' | 'PATCH' | 'DELETE';
  body?: unknown;
  idempotencyKey?: string;
  hospitalOrgId?: string;
}

export class ClaimDeskError extends Error {
  public readonly status: number;
  public readonly code: string;
  public readonly details?: unknown;

  constructor(status: number, code: string, message: string, details?: unknown) {
    super(message);
    this.name = 'ClaimDeskError';
    this.status = status;
    this.code = code;
    this.details = details;
  }
}

export class ClaimDeskClient {
  private readonly apiKey: string;
  private readonly orgId: string;
  private readonly baseUrl: string;
  private readonly actingHospitalOrgId?: string;

  constructor(options: ClaimDeskClientOptions) {
    this.apiKey = options.apiKey;
    this.orgId = options.orgId;
    this.baseUrl = (options.baseUrl || DEFAULT_CLAIMDESK_BASE_URL).replace(/\/$/, '');
    this.actingHospitalOrgId = options.actingHospitalOrgId;
  }

  private async request<T = unknown>(path: string, opts: ClaimDeskRequestOptions = {}): Promise<T> {
    const method = opts.method || 'GET';
    const headers: Record<string, string> = {
      Authorization: `Bearer ${this.apiKey}`,
      'X-ClaimDesk-Org-ID': this.orgId,
    };

    const hospId = opts.hospitalOrgId || this.actingHospitalOrgId;
    if (hospId) {
      headers['X-ClaimDesk-Hospital-ID'] = hospId;
    }

    if (opts.body !== undefined) {
      headers['Content-Type'] = 'application/json';
    }
    if (method === 'POST' || method === 'PATCH') {
      headers['Idempotency-Key'] = opts.idempotencyKey || crypto.randomUUID();
    }

    const res = await fetch(`${this.baseUrl}${path}`, {
      method,
      headers,
      body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
    });

    const json = (await res.json().catch(() => ({}))) as {
      error?: { code?: string; message?: string; details?: unknown };
    };

    if (!res.ok) {
      throw new ClaimDeskError(
        res.status,
        json.error?.code || 'API_ERROR',
        json.error?.message || `ClaimDesk request failed with HTTP ${res.status}`,
        json.error?.details
      );
    }
    return json as T;
  }

  /** List HMOs and accessible facilities */
  listOrganizations() {
    return this.request('/v1/organizations');
  }

  /**
   * Programmatically provision a child HOSPITAL under an HMS_PARTNER org.
   * Pass issue_api_key: true to receive a dedicated hospital-scoped cd_live_... key immediately.
   */
  provisionHospital(
    payload: {
      name: string;
      nhia_code?: string;
      tier?: 'PRIMARY' | 'SECONDARY' | 'TERTIARY';
      webhook_url?: string;
      live_webhook_enabled?: boolean;
      issue_api_key?: boolean;
      api_key_label?: string;
    },
    idempotencyKey?: string
  ) {
    return this.request('/v1/organizations', {
      method: 'POST',
      body: { ...payload, type: 'HOSPITAL' },
      idempotencyKey,
    });
  }

  /** Lookup active contracted HMO tariffs for a specific encounter date */
  getTariffs(params: {
    hmo_id: string;
    hospital_id?: string;
    plan_tier?: string;
    encounter_date?: string;
    include_history?: boolean;
  }) {
    const q = new URLSearchParams({ hmo_id: params.hmo_id });
    if (params.hospital_id) q.set('hospital_id', params.hospital_id);
    if (params.plan_tier) q.set('plan_tier', params.plan_tier);
    if (params.encounter_date) q.set('encounter_date', params.encounter_date);
    if (params.include_history) q.set('include_history', 'true');
    return this.request(`/v1/tariffs?${q.toString()}`);
  }

  /** Request a Pre-Authorization (starts NHIA 1-hour SLA clock, or 48h emergency retro) */
  requestPreAuthorization(
    payload: {
      hospital_org_id?: string;
      hmo_org_id: string;
      external_ref_id?: string;
      enrollee_id: string;
      enrollee_nin?: string;
      patient_consent_ref: string;
      plan_tier: string;
      icd10_code: string;
      icd11_code?: string;
      clinical_summary: string;
      is_emergency?: boolean;
      requested_services: Array<{
        service_code: string;
        service_name: string;
        quantity: number;
        estimated_kobo: number;
      }>;
    },
    idempotencyKey?: string
  ) {
    return this.request('/v1/pre-authorizations', {
      method: 'POST',
      body: payload,
      idempotencyKey,
    });
  }

  /** Scrub a draft claim for PA, tariff ceiling, ICD-10 medical necessity & 90/10 co-pay math */
  scrubClaim(payload: {
    hospital_org_id?: string;
    hmo_org_id: string;
    enrollee_id: string;
    plan_tier: string;
    encounter_date: string;
    icd10_code: string;
    icd11_code?: string;
    pa_code?: string | null;
    external_ref_id?: string;
    patient_consent_ref: string;
    line_items: Array<{ service_code: string; quantity: number; billed_unit_kobo: number }>;
  }) {
    return this.request('/v1/claims/scrub', { method: 'POST', body: payload });
  }

  /** Submit a scrubbed claim to the target HMO */
  submitClaim(payload: Record<string, unknown>, idempotencyKey?: string) {
    return this.request('/v1/claims', {
      method: 'POST',
      body: payload,
      idempotencyKey,
    });
  }

  /** Upload a clinical attachment (PDF/PNG/JPEG/TXT up to 2 MB) to a PA or Claim */
  uploadAttachment(payload: {
    resource_type: 'PRE_AUTHORIZATION' | 'CLAIM';
    resource_id: string;
    file_name: string;
    content_type: string;
    content_base64: string;
  }) {
    return this.request('/v1/attachments', { method: 'POST', body: payload });
  }

  /** List NIP settlement batches & remittance advices */
  listSettlements() {
    return this.request('/v1/settlements');
  }

  /** Reconcile a bank credit CSV statement against NIP settlement batches & open claims */
  reconcileBankStatementCsv(csv: string) {
    return this.request('/v1/settlements/reconcile-csv', { method: 'POST', body: { csv } });
  }

  /** Fetch HMO Payer Performance Scorecard & 30/60/90+ day Aging Receivables */
  getHmoScorecard() {
    return this.request('/v1/analytics/scorecard');
  }

  /** Bulk import hospital's own contracted HMO tariff sheet (CSV) */
  importTariffsCsv(payload: { hmo_org_id: string; hospital_org_id?: string; csv: string }) {
    return this.request('/v1/tariffs/import-csv', { method: 'POST', body: payload });
  }

  /** Record external HMO PA code or rejection received via WhatsApp/Email/Phone/HMO Portal */
  recordExternalPaResponse(
    paId: string,
    payload: {
      decision: 'APPROVED' | 'REJECTED';
      external_pa_code?: string;
      response_channel?: 'WHATSAPP' | 'EMAIL' | 'HMO_PORTAL' | 'PHONE';
      rejection_reason?: string;
    },
    idempotencyKey?: string
  ) {
    return this.request(`/v1/pre-authorizations/${paId}/record-response`, {
      method: 'PATCH',
      body: payload,
      idempotencyKey,
    });
  }

  /** Record an external NIP bank payout received from an HMO against submitted claims */
  recordExternalSettlement(
    payload: {
      hmo_org_id: string;
      claim_ids: string[];
      nip_session_id?: string;
      total_paid_kobo: number;
      bank_name?: string;
      notes?: string;
    },
    idempotencyKey?: string
  ) {
    return this.request('/v1/settlements/record-external', {
      method: 'POST',
      body: payload,
      idempotencyKey,
    });
  }
}

/**
 * Verifies an incoming ClaimDesk HMAC-SHA256 webhook signature.
 * Pass the raw UTF-8 request body (before JSON.parse), X-ClaimDesk-Timestamp,
 * X-ClaimDesk-Signature, and your org's whsec_... signing secret.
 */
export async function verifyClaimDeskWebhook(params: {
  rawBody: string;
  timestampHeader: string;
  signatureHeader: string;
  webhookSecret: string;
  maxAgeSeconds?: number;
}): Promise<boolean> {
  const { rawBody, timestampHeader, signatureHeader, webhookSecret, maxAgeSeconds = 300 } = params;
  if (!timestampHeader || !signatureHeader || !webhookSecret) return false;

  const tsSec = Number(timestampHeader);
  if (!Number.isFinite(tsSec)) return false;
  if (Math.abs(Math.floor(Date.now() / 1000) - tsSec) > maxAgeSeconds) {
    return false;
  }

  const encoder = new TextEncoder();
  const key = await crypto.subtle.importKey(
    'raw',
    encoder.encode(webhookSecret),
    { name: 'HMAC', hash: 'SHA-256' },
    false,
    ['sign']
  );
  const sigBuf = await crypto.subtle.sign('HMAC', key, encoder.encode(`${timestampHeader}.${rawBody}`));
  const expected =
    'sha256=' +
    Array.from(new Uint8Array(sigBuf))
      .map((b) => b.toString(16).padStart(2, '0'))
      .join('');

  if (expected.length !== signatureHeader.length) return false;
  let diff = 0;
  for (let i = 0; i < expected.length; i++) {
    diff |= expected.charCodeAt(i) ^ signatureHeader.charCodeAt(i);
  }
  return diff === 0;
}
