/**
 * System-event communications wiring — customers module (Task 13).
 *
 * This helper is the SINGLE auto-insert path for system-generated
 * `customer_communications` rows. The notifications pipeline
 * (`system-communications-notifications`) MUST call this when emitting
 * customer-facing events (invoice sent, portal invitation, proposal viewed/accepted).
 *
 * Contract:
 *  - System events insert via `recordSystemCommunication` (created_by = NULL).
 *  - Staff emails and manual notes insert via the Task 7 API route.
 *  - No duplicate inserts: every system event calls this exactly once.
 */
import type { Db } from '../client'
import { appendCustomerCommunication, type CustomerCommunication } from './customers'

export async function recordSystemCommunication(
  db: Db,
  input: {
    tenantId: string
    customerId: string
    direction: 'outbound' | 'inbound'
    channel: 'email' | 'system' | 'ticket'
    subject?: string
    body?: string
    fromAddress?: string
    toAddress?: string
    relatedId?: string
    relatedType?: string
  },
): Promise<CustomerCommunication> {
  return appendCustomerCommunication(db, input.tenantId, input.customerId, {
    direction: input.direction,
    channel: input.channel,
    subject: input.subject ?? null,
    body: input.body ?? null,
    fromAddress: input.fromAddress ?? null,
    toAddress: input.toAddress ?? null,
    relatedId: input.relatedId ?? null,
    relatedType: input.relatedType ?? null,
    // created_by NULL signals system-generated row
    createdBy: null,
  })
}
