import { createDbService } from '@/server/services/db.js';
import { sendEmail } from '@/server/email/resend.js';
import { resolveAdminSupportRecipients } from '@/server/support/notifications-admin.js';
import { buildAlertReact } from '../render.js';
import { redactError } from '../redact.js';
import type {
  ChannelAdapter,
  AlertPayload,
  AlertChannelRow,
  MonitorEnv,
  ChannelSendResult,
} from '../types.js';

export const email: ChannelAdapter = {
  kind: 'email',
  async send(
    payload: AlertPayload,
    channel: AlertChannelRow,
    env: MonitorEnv,
  ): Promise<ChannelSendResult> {
    try {
      if (!env.RESEND_API_KEY || !env.RESEND_FROM_EMAIL) {
        return { ok: false, error: 'RESEND not configured' };
      }
      const cfgRecipients = (channel.config as { recipients?: string[] })?.recipients;
      let recipients: string[];
      if (cfgRecipients && cfgRecipients.length > 0) {
        recipients = cfgRecipients;
      } else {
        const db = createDbService({ DATABASE_URL: env.DATABASE_URL });
        recipients = await resolveAdminSupportRecipients(db, env as never);
      }
      if (recipients.length === 0) return { ok: false, error: 'no recipients' };

      const react = buildAlertReact(payload);
      let anyOk = false;
      let lastErr: string | undefined;
      for (const to of recipients) {
        const res = await sendEmail(
          {
            RESEND_API_KEY: env.RESEND_API_KEY,
            RESEND_FROM_EMAIL: env.RESEND_FROM_EMAIL,
            ENVIRONMENT: env.ENVIRONMENT,
            EMAIL_MOCK_DB: env.EMAIL_MOCK_DB,
          },
          { to, subject: payload.subject, react },
        );
        if (res.success) anyOk = true;
        else lastErr = res.error;
      }
      return anyOk ? { ok: true } : { ok: false, error: lastErr ?? 'all sends failed' };
    } catch (err) {
      return { ok: false, error: redactError(err, 'email send failed') };
    }
  },
};
