import { randomUUID } from 'node:crypto';
import type { IntegrationEnvironment } from '@/lib/integrations/environment';
import { createLeadDestinationAdapter, type LeadDestinationAdapter } from './adapters';
import { executeIdempotent } from './idempotency';
import type { DemoLead, DemoSubmissionResult } from './schema';

export interface SubmitDemoOptions {
  environment: IntegrationEnvironment;
  adapter?: LeadDestinationAdapter;
  testScenario?: 'success' | 'duplicate' | 'timeout' | 'integration-error';
}

export async function submitDemoLead(
  lead: DemoLead,
  options: SubmitDemoOptions,
): Promise<DemoSubmissionResult> {
  const { environment } = options;
  const adapter = options.adapter ?? createLeadDestinationAdapter(environment);

  return executeIdempotent(
    lead.idempotencyKey,
    environment.DEMO_IDEMPOTENCY_TTL_SECONDS,
    async () => {
      const correlationId = randomUUID();
      const controller = new AbortController();
      const timeout = setTimeout(() => controller.abort(), environment.DEMO_REQUEST_TIMEOUT_MS);

      try {
        const destinationResult = await adapter.submitLead(lead, {
          correlationId,
          idempotencyKey: lead.idempotencyKey,
          signal: controller.signal,
          environment: environment.NODE_ENV,
          ...(options.testScenario ? { testScenario: options.testScenario } : {}),
        });

        if (!destinationResult.ok) {
          return {
            ok: false,
            category: destinationResult.category,
            formErrorCode: destinationResult.code,
            retryable: destinationResult.retryable,
            correlationId,
          };
        }

        return {
          ok: true,
          submissionId: destinationResult.externalId,
          acceptedAt: destinationResult.acceptedAt,
          nextAction: { type: 'success', mode: destinationResult.mode },
        };
      } catch (error) {
        const timedOut =
          controller.signal.aborted ||
          (error instanceof DOMException && error.name === 'AbortError');
        return {
          ok: false,
          category: timedOut ? 'timeout' : 'integration',
          formErrorCode: timedOut ? 'lead_destination_timeout' : 'lead_destination_failure',
          retryable: true,
          correlationId,
        };
      } finally {
        clearTimeout(timeout);
      }
    },
  );
}
