import {
  Column,
  CreateDateColumn,
  DeleteDateColumn,
  Entity,
  Index,
  JoinColumn,
  ManyToOne,
  PrimaryGeneratedColumn,
  UpdateDateColumn,
} from 'typeorm';
import { ProgramRegistration } from './program-registration.entity';
import { WorkflowStage } from './workflow-stage.entity';
import { User } from './user.entity';
import { Auditable } from 'src/audit-history/decorators/auditable.decorator';
import { SkipAudit } from 'src/audit-history/decorators/skip-audit.decorator';

@Entity('registration_workflow_stage')
@Index('idx_registration_workflow_stage_registration', ['registration'])
@Auditable()
export class RegistrationWorkflowStage {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ name: 'registration_id', type: 'int' })
  registrationId: number;

  @SkipAudit()
  @ManyToOne(() => ProgramRegistration, { nullable: false })
  @JoinColumn({ name: 'registration_id' })
  registration: ProgramRegistration;

  @Column({ name: 'workflow_stage_id', type: 'int' })
  workflowStageId: number;

  @SkipAudit()
  @ManyToOne(() => WorkflowStage, workflowStage => workflowStage.registrationWorkflowStages, {
    nullable: false
  })
  @JoinColumn({ name: 'workflow_stage_id' })
  workflowStage: WorkflowStage;

  @Column({ name: 'workflow_stage_key', type: 'varchar', length: 100 })
  workflowStageKey: string;

  @Column({ type: 'varchar', length: 50, default: 'pending' })
  status: string;

  @Column({ name: 'completed_at', type: 'timestamptz', nullable: true })
  completedAt: Date | null;

  @Column({ name: 'completion_data', type: 'jsonb', nullable: true })
  completionData: Record<string, unknown> | null;

  @Column({ type: 'jsonb', nullable: true })
  metadata: Record<string, unknown> | null;

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

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

  @DeleteDateColumn({ name: 'deleted_at', type: 'timestamptz', nullable: true })
  deletedAt: Date | null;

  @SkipAudit()
  @Column({ name: 'created_by', type: 'int', nullable: true })
  createdById: number | null;

  @SkipAudit()
  @ManyToOne(() => User, { nullable: true })
  @JoinColumn({ name: 'created_by' })
  createdBy: User | null;

  @SkipAudit()
  @Column({ name: 'updated_by', type: 'int', nullable: true })
  updatedById: number | null;

  @SkipAudit()
  @ManyToOne(() => User, { nullable: true })
  @JoinColumn({ name: 'updated_by' })
  updatedBy: User | null;

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