import { Entity, Column, Index } from 'typeorm';
import { BaseEntity } from '../database/base.entity';

/**
 * Tenant-configurable communication template.
 *
 * Context is fixed by the calling surface (Query page → 'QUERY',
 * Booking page → 'BOOKING', Movement Dashboard → 'MOVEMENT'). The
 * user picks a template only when multiple exist within the same
 * (channel, context) bucket; otherwise the `is_default` row wins.
 *
 * body_template holds the mustache-lite source. The renderer walks
 * a JSON bag built by a per-context resolver and substitutes tokens
 * inline.
 *
 * See migration 1782500000000-CommunicationTemplates for the
 * partial-unique index that enforces "one default per bucket".
 */
export type CommunicationChannel = 'EMAIL' | 'WHATSAPP';
export type CommunicationContext =
  | 'QUERY'
  | 'BOOKING'
  | 'MOVEMENT_CUSTOMER'
  | 'MOVEMENT_SUPPLIER';

@Entity('communication_templates')
@Index(['tenant_id', 'channel', 'context'])
export class CommunicationTemplateEntity extends BaseEntity {
  @Column({ type: 'varchar', length: 20 })
  channel: CommunicationChannel;

  @Column({ type: 'varchar', length: 20 })
  context: CommunicationContext;

  @Column({ type: 'varchar', length: 120 })
  name: string;

  // Nullable — subject only applies to EMAIL rows. The DB CHECK
  // constraint enforces "EMAIL row must have subject" at the schema
  // layer; the service layer mirrors that when saving.
  @Column({ type: 'varchar', length: 200, nullable: true })
  subject: string | null;

  @Column({ type: 'text' })
  body_template: string;

  @Column({ type: 'boolean', default: false })
  is_default: boolean;

  @Column({ type: 'boolean', default: true })
  is_active: boolean;
}
