// Which events exist is CODE (each has a context builder in NotificationService);
// their templates/recipients/enablement are DATA. This metadata drives the admin
// template editor (available placeholders) and is Nest-free so the router can
// import it without pulling framework code.
export interface EventMeta {
  event: string;
  label: string;
  relatedType: 'INVOICE' | 'RECEIPT' | 'MAINTENANCE_REQUEST' | 'STATEMENT';
  placeholders: string[];
}

export const NOTIFICATION_EVENTS: EventMeta[] = [
  { event: 'INVOICE_ISSUED', label: 'Invoice issued', relatedType: 'INVOICE', placeholders: ['tenantName', 'invoiceNumber', 'amount', 'dueDate', 'period'] },
  { event: 'RECEIPT_APPROVED', label: 'Payment approved', relatedType: 'RECEIPT', placeholders: ['tenantName', 'receiptNumber', 'amount', 'date'] },
  { event: 'RECEIPT_REJECTED', label: 'Payment rejected', relatedType: 'RECEIPT', placeholders: ['tenantName', 'receiptNumber', 'amount', 'date', 'reason'] },
  { event: 'RECEIPT_BOUNCED', label: 'Payment dishonoured', relatedType: 'RECEIPT', placeholders: ['tenantName', 'receiptNumber', 'amount', 'date'] },
  { event: 'MAINTENANCE_STATUS_CHANGED', label: 'Maintenance status changed', relatedType: 'MAINTENANCE_REQUEST', placeholders: ['tenantName', 'title', 'status', 'property', 'unit'] },
  { event: 'STATEMENT_SENT', label: 'Monthly statement sent', relatedType: 'STATEMENT', placeholders: ['tenantName', 'leaseReference', 'period', 'balance'] },
];

export const NOTIFICATION_CHANNELS = ['EMAIL', 'SMS'];
export const NOTIFICATION_RECIPIENTS = ['TENANT', 'STAFF'];

/** Handlebars-lite: replace {{ key }} with the context value (missing → blank).
 * Uses an own-property check so inherited names (constructor, toString, __proto__)
 * resolve to blank, not the inherited member. */
export function renderTemplate(template: string, context: Record<string, string>): string {
  return template.replace(/\{\{\s*(\w+)\s*\}\}/g, (_, key: string) =>
    Object.prototype.hasOwnProperty.call(context, key) ? context[key] : '',
  );
}

export interface NotifyPayload {
  event: string;
  organizationId: string;
  relatedType: string;
  relatedId: string;
}
