/**
 * Approval Instance Entity
 * Instancias de flujos de aprobacion activos.
 *
 * @module Documents (MAE-016)
 */

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  ManyToOne,
  OneToMany,
  JoinColumn,
  Index,
} from 'typeorm';
import { ApprovalWorkflow } from './approval-workflow.entity';
import { Document } from './document.entity';
import { DocumentVersion } from './document-version.entity';
import { ApprovalStep } from './approval-step.entity';

export type WorkflowStatus =
  | 'draft'
  | 'pending'
  | 'in_progress'
  | 'approved'
  | 'rejected'
  | 'cancelled';

export type ApprovalAction = 'approve' | 'reject' | 'request_changes';

@Entity('approval_instances', { schema: 'documents' })
@Index(['tenantId'])
@Index(['documentId'])
@Index(['status'])
export class ApprovalInstance {
  @PrimaryGeneratedColumn('uuid')
  id!: string;

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

  // Flujo y documento
  @Column({ name: 'workflow_id', type: 'uuid' })
  workflowId!: string;

  @ManyToOne(() => ApprovalWorkflow)
  @JoinColumn({ name: 'workflow_id' })
  workflow!: ApprovalWorkflow;

  @Column({ name: 'document_id', type: 'uuid' })
  documentId!: string;

  @ManyToOne(() => Document)
  @JoinColumn({ name: 'document_id' })
  document!: Document;

  @Column({ name: 'version_id', type: 'uuid', nullable: true })
  versionId?: string;

  @ManyToOne(() => DocumentVersion, { nullable: true })
  @JoinColumn({ name: 'version_id' })
  version?: DocumentVersion;

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

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

  @Column({ name: 'total_steps', type: 'int' })
  totalSteps!: number;

  // 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;

  // Iniciador
  @Column({ name: 'initiated_by_id', type: 'uuid', nullable: true })
  initiatedById?: string;

  @Column({ name: 'initiated_by_name', length: 255, nullable: true })
  initiatedByName?: string;

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

  @Column({ name: 'final_comments', type: 'text', nullable: true })
  finalComments?: string;

  @Column({ name: 'final_approver_id', type: 'uuid', nullable: true })
  finalApproverId?: string;

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

  @Column({ type: 'jsonb', nullable: true })
  metadata?: Record<string, any>;

  // Relaciones
  @OneToMany(() => ApprovalStep, (step) => step.instance)
  steps?: ApprovalStep[];

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

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