/**
 * Approval Step Entity
 * Pasos de aprobacion por instancia.
 *
 * @module Documents (MAE-016)
 */

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  ManyToOne,
  OneToMany,
  JoinColumn,
  Index,
} from 'typeorm';
import { ApprovalInstance, WorkflowStatus, ApprovalAction } from './approval-instance.entity';
import { ApprovalActionEntity } from './approval-action.entity';

export type ApprovalStepType = 'review' | 'approval' | 'signature' | 'comment';

@Entity('approval_steps', { schema: 'documents' })
@Index(['instanceId'])
@Index(['status'])
export class ApprovalStep {
  @PrimaryGeneratedColumn('uuid')
  id!: string;

  @Column({ name: 'tenant_id', type: 'uuid' })
  tenantId!: string;

  // Instancia
  @Column({ name: 'instance_id', type: 'uuid' })
  instanceId!: string;

  @ManyToOne(() => ApprovalInstance, (instance) => instance.steps, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'instance_id' })
  instance!: ApprovalInstance;

  // Paso
  @Column({ name: 'step_number', type: 'int' })
  stepNumber!: number;

  @Column({ name: 'step_name', length: 255 })
  stepName!: string;

  @Column({
    name: 'step_type',
    type: 'enum',
    enum: ['review', 'approval', 'signature', 'comment'],
    enumName: 'approval_step_type',
  })
  stepType!: ApprovalStepType;

  // Aprobadores requeridos
  @Column({ name: 'required_approvers', type: 'uuid', array: true, nullable: true })
  requiredApprovers?: string[];

  @Column({ name: 'required_count', type: 'int', default: 1 })
  requiredCount!: number;

  // Estado
  @Column({
    type: 'enum',
    enum: ['draft', 'pending', 'in_progress', 'approved', 'rejected', 'cancelled'],
    enumName: 'workflow_status',
    default: 'pending',
  })
  status!: WorkflowStatus;

  // Fechas
  @Column({ name: 'started_at', type: 'timestamptz', nullable: true })
  startedAt?: Date;

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

  @Column({ name: 'due_date', type: 'timestamptz', nullable: true })
  dueDate?: Date;

  // Resultado
  @Column({
    name: 'action_taken',
    type: 'enum',
    enum: ['approve', 'reject', 'request_changes'],
    enumName: 'approval_action',
    nullable: true,
  })
  actionTaken?: ApprovalAction;

  @Column({ name: 'approved_by', type: 'uuid', array: true, nullable: true })
  approvedBy?: string[];

  @Column({ name: 'rejected_by', type: 'uuid', array: true, nullable: true })
  rejectedBy?: string[];

  // Notas
  @Column({ type: 'text', nullable: true })
  notes?: string;

  // Relaciones
  @OneToMany(() => ApprovalActionEntity, (action) => action.step)
  actions?: ApprovalActionEntity[];

  // Auditoria
  @CreateDateColumn({ name: 'created_at', type: 'timestamptz' })
  createdAt!: Date;

  @UpdateDateColumn({ name: 'updated_at', type: 'timestamptz' })
  updatedAt!: Date;
}
