import { Injectable } from '@nestjs/common';
import type { ScopeVector } from '@insignia/iios-contracts';
import { WebhookAdapter, EmailAdapter, type ChannelAdapter } from '@insignia/iios-adapter-sdk';

export interface AdapterConfig {
  secret: string;
  scope: ScopeVector;
}

/**
 * Registers channel adapters + their per-channel config (secret + scope). EMAIL uses
 * the email-native EmailAdapter (RFC threading); the rest use the reference
 * WebhookAdapter. Secrets come from ADAPTER_SECRETS (JSON map); scope defaults to demo.
 */
@Injectable()
export class AdapterRegistry {
  private readonly adapters = new Map<string, { adapter: ChannelAdapter; config: AdapterConfig }>();

  constructor() {
    let secrets: Record<string, string> = {};
    try {
      secrets = JSON.parse(process.env.ADAPTER_SECRETS ?? '{}');
    } catch {
      secrets = {};
    }
    const scope: ScopeVector = {
      orgId: process.env.ADAPTER_ORG ?? 'org_portal-demo',
      appId: process.env.ADAPTER_APP ?? 'portal-demo',
    };
    for (const channelType of ['WEBHOOK', 'EMAIL', 'WHATSAPP', 'PORTAL']) {
      const adapter: ChannelAdapter = channelType === 'EMAIL' ? new EmailAdapter() : new WebhookAdapter(channelType);
      this.adapters.set(channelType, {
        adapter,
        config: { secret: secrets[channelType] ?? 'dev-adapter-secret', scope },
      });
    }
  }

  get(channelType: string): { adapter: ChannelAdapter; config: AdapterConfig } | undefined {
    return this.adapters.get(channelType);
  }
}
