import type { ChannelSettings } from '@wa-ticketing/shared';
import { sql } from '../db.js';
import { sendSmtpMail } from './emailService.js';
import { sendTwilioSms } from './twilioSmsService.js';
import { auditService } from './auditService.js';

/**
 * Staff notifications when a customer sends an inbound message (WhatsApp, web, email).
 * Respects per-channel SMS / email toggles and escalation order (email then SMS).
 */
export async function notifyInboundAlerts(opts: {
  ticketId: string;
  channelId: string;
  channelName: string;
  fromLabel: string;
  preview: string;
  settings: ChannelSettings;
}): Promise<{ flaggedEscalation: boolean }> {
  const a = opts.settings.alerts;
  const summary = `Channel: ${opts.channelName}\nFrom: ${opts.fromLabel}\n\n${opts.preview.slice(0, 2000)}\n\nTicket id: ${opts.ticketId}`;

  const emailStaff = async () => {
    if (!a.email.enabled || !a.email.address.trim()) return;
    const r = await sendSmtpMail({
      to: a.email.address.trim(),
      subject: `[${opts.channelName}] New inbound message`,
      text: summary,
    });
    await auditService.log(null, 'system', r.ok ? 'channel.alert_email_sent' : 'channel.alert_email_failed', 'ticket', opts.ticketId, {
      channelId: opts.channelId,
      error: r.error,
    });
  };

  const smsStaff = async () => {
    if (!a.sms.enabled || !a.sms.phone_e164.trim()) return;
    const r = await sendTwilioSms({
      to: a.sms.phone_e164.trim(),
      body: `${opts.channelName}: ${opts.fromLabel} — ${opts.preview.slice(0, 100)}`,
    });
    await auditService.log(null, 'system', r.ok ? 'channel.alert_sms_sent' : 'channel.alert_sms_failed', 'ticket', opts.ticketId, {
      channelId: opts.channelId,
      error: r.error,
    });
  };

  const esc = a.escalation.enabled;
  const sequential = esc && a.escalation.emailThenSms;

  if (sequential) {
    await emailStaff();
    await smsStaff();
  } else {
    await Promise.all([emailStaff(), smsStaff()]);
  }

  let flaggedEscalation = false;
  if (esc && a.escalation.flagTicketForEscalation) {
    await sql`
      UPDATE tickets SET needs_escalation = true, updated_at = NOW() WHERE id = ${opts.ticketId}
    `;
    flaggedEscalation = true;
  }
  return { flaggedEscalation };
}

