import type { CapabilityProvider, CapabilityRequest, ProviderResult } from '@insignia/iios-contracts';

/**
 * A real egress provider: POSTs the outbound command to a configured URL. Activated
 * only when `IIOS_PROVIDER_URL_<CHANNELTYPE>` is set — proving "flip the binding →
 * it really sends" without hardcoding any specific vendor. A transport failure is
 * surfaced as FAILED (never thrown), per the adapter doctrine.
 */
export class HttpProvider implements CapabilityProvider {
  readonly name = 'http';
  readonly channelTypes: string[];
  readonly capabilities = { canSend: true };

  constructor(
    channelType: string,
    private readonly url: string,
  ) {
    this.channelTypes = [channelType];
  }

  async send(req: CapabilityRequest): Promise<ProviderResult> {
    const started = Date.now();
    try {
      const res = await fetch(this.url, {
        method: 'POST',
        headers: { 'content-type': 'application/json', 'idempotency-key': req.idempotencyKey },
        body: JSON.stringify({ channelType: req.channelType, target: req.target, payload: req.payload }),
      });
      const latencyMs = Date.now() - started;
      if (!res.ok) return { providerRef: `http-${res.status}`, outcome: 'FAILED', errorCode: `HTTP_${res.status}`, latencyMs };
      return { providerRef: `http-${req.channelType}-${req.idempotencyKey}`, outcome: 'SENT', latencyMs };
    } catch (err) {
      return { providerRef: 'http-error', outcome: 'FAILED', errorCode: (err as Error).message.slice(0, 60), latencyMs: Date.now() - started };
    }
  }
}
