import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
} from 'typeorm';
import { SessionCommunicationPurposeEnum } from '../enum/session-communication-purpose.enum';
import { SessionCommunicationStatusEnum } from '../enum/session-communication-status.enum';

/**
 * Append-only history of session bulk-communication sends. One row is written per send,
 * keyed by (program, session, purpose) — both channels (email + whatsapp) are aggregated
 * into the counts on the single row. `sessionId` is null for program-level purposes
 * (Welcome, Program completion), which are sent for the whole program, not a session.
 *
 * This is a track table (like hdb_communication_track): rows are never mutated or
 * soft-deleted, so it carries no deletedAt.
 */
@Entity('hdb_session_communication_status')
@Index('idx_session_comm_status_program_session', ['programId', 'sessionId'])
@Index('idx_session_comm_status_program_purpose', ['programId', 'purpose'])
export class SessionCommunicationStatus {
  @PrimaryGeneratedColumn('increment', { type: 'bigint' })
  id: number;

  @Column({ name: 'program_id', type: 'bigint' })
  programId: number;

  @Column({ name: 'session_id', type: 'bigint', nullable: true })
  sessionId: number | null;

  @Column({ name: 'purpose', type: 'varchar', length: 40 })
  purpose: SessionCommunicationPurposeEnum;

  @Column({ name: 'occurrence', type: 'varchar', length: 20, nullable: true })
  occurrence: string | null;

  @Column({ name: 'status', type: 'varchar', length: 30 })
  status: SessionCommunicationStatusEnum;

  @Column({ name: 'requested_count', type: 'int' })
  requestedCount: number;

  @Column({ name: 'email_enqueued_count', type: 'int' })
  emailEnqueuedCount: number;

  @Column({ name: 'whatsapp_enqueued_count', type: 'int' })
  whatsappEnqueuedCount: number;

  @Column({ name: 'skipped_count', type: 'int' })
  skippedCount: number;

  @CreateDateColumn({ name: 'created_at', type: 'timestamptz', default: () => 'CURRENT_TIMESTAMP' })
  createdAt: Date;

  @UpdateDateColumn({
    name: 'updated_at',
    type: 'timestamptz',
    default: () => 'CURRENT_TIMESTAMP',
    onUpdate: 'CURRENT_TIMESTAMP',
  })
  updatedAt: Date;

  @Column({ name: 'created_by', type: 'bigint', nullable: true })
  createdBy: number | null;

  @Column({ name: 'updated_by', type: 'bigint', nullable: true })
  updatedBy: number | null;

  constructor(partial: Partial<SessionCommunicationStatus>) {
    Object.assign(this, partial);
  }
}
