/**
 * Approval Workflow Entity
 * Definicion de flujos de aprobacion para documentos.
 *
 * @module Documents (MAE-016)
 */

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  ManyToOne,
  JoinColumn,
  Index,
} from 'typeorm';
import { DocumentCategory } from './document-category.entity';
import { DocumentType } from './document.entity';

@Entity('approval_workflows', { schema: 'documents' })
@Index(['tenantId', 'workflowCode'], { unique: true })
@Index(['tenantId', 'categoryId'])
export class ApprovalWorkflow {
  @PrimaryGeneratedColumn('uuid')
  id!: string;

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

  // Identificacion
  @Column({ name: 'workflow_code', length: 50 })
  workflowCode!: string;

  @Column({ length: 255 })
  name!: string;

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

  // Aplica a
  @Column({ name: 'category_id', type: 'uuid', nullable: true })
  categoryId?: string;

  @ManyToOne(() => DocumentCategory, { nullable: true })
  @JoinColumn({ name: 'category_id' })
  category?: DocumentCategory;

  @Column({
    name: 'document_type',
    type: 'enum',
    enum: ['plan', 'specification', 'contract', 'permit', 'report', 'photograph', 'drawing', 'manual', 'procedure', 'form', 'correspondence', 'invoice', 'estimate', 'other'],
    enumName: 'document_type',
    nullable: true,
  })
  documentType?: DocumentType;

  // Pasos (JSON array)
  @Column({ type: 'jsonb' })
  steps!: Array<{
    stepNumber: number;
    name: string;
    type: 'review' | 'approval' | 'signature' | 'comment';
    approvers: string[];
    requiredCount: number;
  }>;

  // Configuracion
  @Column({ name: 'allow_parallel', type: 'boolean', default: false })
  allowParallel!: boolean;

  @Column({ name: 'allow_skip', type: 'boolean', default: false })
  allowSkip!: boolean;

  @Column({ name: 'auto_archive_on_approval', type: 'boolean', default: false })
  autoArchiveOnApproval!: boolean;

  // Estado
  @Column({ name: 'is_active', type: 'boolean', default: true })
  isActive!: boolean;

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

  // Auditoria
  @Column({ name: 'created_by', type: 'uuid', nullable: true })
  createdBy?: string;

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

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

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

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