import type { DispatchEnv } from '../../workflows/outbox/types.js';
import type { DrizzleClient } from '../../db/client.js';
import { insertOutboxRow } from '../../db/queries/outbox.js';
import { resolveCaseRecipient } from './resolve-case-recipient.js';

type CaseTemplateKey =
  | 'support.case_opened'
  | 'support.escalated_to_human'
  | 'support.case_resolved'
  | 'support.vendor_offered'
  | 'support.customer_decided'
  | 'support.reopened';

export async function enqueueCaseEmail(
  env: DispatchEnv,
  tx: DrizzleClient,
  args: {
    caseId: string;
    templateKey: CaseTemplateKey;
    recipients: Array<'customer' | 'vendor'>;
    siteEmails?: string[];
    params: Record<string, unknown>;
    customerLocale?: 'he' | 'en';
    vendorLocale?: 'he' | 'en';
  },
): Promise<void> {
  for (const role of args.recipients) {
    const email = await resolveCaseRecipient(env, args.caseId, role);
    if (!email) continue;
    const locale =
      role === 'customer' ? (args.customerLocale ?? 'he') : (args.vendorLocale ?? 'he');
    await insertOutboxRow(tx, {
      aggregateType: 'case',
      aggregateId: args.caseId,
      eventType: 'support.notif.email',
      payload: {
        to: email,
        templateKey: args.templateKey,
        params: { caseId: args.caseId, recipientRole: role, ...args.params },
        locale,
      },
    });
  }
  for (const to of args.siteEmails ?? []) {
    await insertOutboxRow(tx, {
      aggregateType: 'case',
      aggregateId: args.caseId,
      eventType: 'support.notif.email',
      payload: {
        to,
        templateKey: args.templateKey,
        params: { caseId: args.caseId, recipientRole: 'site_support', ...args.params },
        locale: 'he',
      },
    });
  }
}
