/**
 * Builds rows for `notification_outbox` from wizard `config` flags.
 * Delivery (SMTP, Slack, cron workers) can read `status = 'pending'` later.
 */

import { randomUUID } from 'node:crypto';

export type MigrationNotifyEvent = 'complete' | 'warning' | 'failure';

const ALLOWED_CHANNELS = new Set(['email', 'slack', 'teams', 'webhook', 'sms']);

function notifyFlagEnabled(config: Record<string, unknown>, event: MigrationNotifyEvent): boolean {
  const key =
    event === 'complete' ? 'notifyOnComplete' : event === 'warning' ? 'notifyOnWarning' : 'notifyOnFailure';
  return config[key] !== false;
}

function normalizedChannels(config: Record<string, unknown>): string[] {
  const raw = config.notifyChannels;
  const list = Array.isArray(raw)
    ? raw.filter((c): c is string => typeof c === 'string' && ALLOWED_CHANNELS.has(c))
    : [];
  return list.length > 0 ? list : ['email'];
}

export function buildOutboxInserts(
  userId: string,
  projectId: string,
  projectName: string,
  config: Record<string, unknown>,
  event: MigrationNotifyEvent,
  detail?: string,
): Array<{
  id: string;
  userId: string;
  projectId: string;
  channel: string;
  event: string;
  payload: Record<string, unknown>;
}> {
  if (!notifyFlagEnabled(config, event)) return [];

  const channels = normalizedChannels(config);
  const payload: Record<string, unknown> = {
    projectId,
    projectName,
    event,
    detail: detail ?? null,
    enqueuedAt: new Date().toISOString(),
  };

  return channels.map((channel) => ({
    id: `ntf-${randomUUID()}`,
    userId,
    projectId,
    channel,
    event,
    payload,
  }));
}
