import { DataSource } from 'typeorm';

import { NotificationsService } from './notifications.service';
import {
  companyNotifyPhoneExpr,
  primaryContactUserJoin,
} from './resolve-company-phone.util';

/**
 * Best-effort SMS + email fan-out to a company's contacts. Looks up the
 * company's phone/email and sends the message over both channels, swallowing
 * per-channel failures so a missing provider never breaks the caller's flow.
 */
export async function sendCompanyChannels(
  dataSource: DataSource,
  notifications: NotificationsService,
  companyId: string,
  message: string,
): Promise<void> {
  const [contact]: Array<{ phone: string | null; email: string | null }> =
    await dataSource.query(
      `SELECT ${companyNotifyPhoneExpr('co')} AS phone, co.email
         FROM freight.companies co
         ${primaryContactUserJoin('co')}
        WHERE co.id = $1 AND co.deleted_at IS NULL`,
      [companyId],
    );
  if (contact?.phone) {
    try {
      await notifications.directSend('sms', contact.phone, message);
    } catch {
      /* best-effort: SMS provider unavailable */
    }
  }
  if (contact?.email) {
    try {
      await notifications.directSend('email', contact.email, message);
    } catch {
      /* best-effort: email provider unavailable */
    }
  }
}
