import type { LeadDestinationAdapter, LeadDestinationResult } from './types';

function abortError(): Error {
  return new DOMException('Operation aborted', 'AbortError');
}

export class LocalLeadDestinationAdapter implements LeadDestinationAdapter {
  readonly name = 'local-discard';

  async submitLead(
    _lead: Parameters<LeadDestinationAdapter['submitLead']>[0],
    context: Parameters<LeadDestinationAdapter['submitLead']>[1],
  ): Promise<LeadDestinationResult> {
    if (context.signal.aborted) throw abortError();

    switch (context.testScenario) {
      case 'duplicate':
        return { ok: false, category: 'duplicate', retryable: false, code: 'local_duplicate' };
      case 'integration-error':
        return { ok: false, category: 'integration', retryable: true, code: 'local_error' };
      case 'timeout':
        await new Promise<void>((resolve, reject) => {
          const timer = setTimeout(resolve, 30_000);
          context.signal.addEventListener(
            'abort',
            () => {
              clearTimeout(timer);
              reject(abortError());
            },
            { once: true },
          );
        });
        break;
      case 'success':
      case undefined:
        break;
    }

    return {
      ok: true,
      externalId: `local_${context.correlationId}`,
      acceptedAt: new Date().toISOString(),
      mode: 'local',
    };
  }
}
