import type {
  IEmailDnsRecord,
  TDnsRecordStatus,
} from '../../ts_interfaces/data/email-domain.js';

type TEmailDnsStatusKey = 'mx' | 'spf' | 'dkim' | 'dmarc';

export interface IBuildEmailDnsRecordsOptions {
  domain: string;
  hostname: string;
  selector?: string;
  dkimValue?: string;
  mxPriority?: number;
  dmarcPolicy?: string;
  dmarcRua?: string;
  statuses?: Partial<Record<TEmailDnsStatusKey, TDnsRecordStatus>>;
}

export function buildEmailDnsRecords(options: IBuildEmailDnsRecordsOptions): IEmailDnsRecord[] {
  const statusFor = (key: TEmailDnsStatusKey): TDnsRecordStatus => options.statuses?.[key] ?? 'unchecked';
  const selector = options.selector || 'default';
  const records: IEmailDnsRecord[] = [
    {
      type: 'MX',
      name: options.domain,
      value: `${options.mxPriority ?? 10} ${options.hostname}`,
      status: statusFor('mx'),
    },
    {
      type: 'TXT',
      name: options.domain,
      value: 'v=spf1 a mx ~all',
      status: statusFor('spf'),
    },
    {
      type: 'TXT',
      name: `_dmarc.${options.domain}`,
      value: `v=DMARC1; p=${options.dmarcPolicy ?? 'none'}; rua=mailto:${options.dmarcRua ?? `dmarc@${options.domain}`}`,
      status: statusFor('dmarc'),
    },
  ];

  if (options.dkimValue) {
    records.splice(2, 0, {
      type: 'TXT',
      name: `${selector}._domainkey.${options.domain}`,
      value: options.dkimValue,
      status: statusFor('dkim'),
    });
  }

  return records;
}
