/**
 * EstimacionWorkflow Entity
 * Historial de workflow de estimaciones
 *
 * @module Estimates
 * @table estimates.estimacion_workflow
 * @ddl schemas/04-estimates-schema-ddl.sql
 */

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  ManyToOne,
  JoinColumn,
  Index,
} from 'typeorm';
import { Tenant } from '../../core/entities/tenant.entity';
import { User } from '../../core/entities/user.entity';
import { Estimacion, EstimateStatus } from './estimacion.entity';

@Entity({ schema: 'estimates', name: 'estimacion_workflow' })
@Index(['tenantId'])
@Index(['estimacionId'])
export class EstimacionWorkflow {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

  @Column({ name: 'estimacion_id', type: 'uuid' })
  estimacionId: string;

  @Column({
    name: 'from_status',
    type: 'enum',
    enum: ['draft', 'submitted', 'reviewed', 'approved', 'invoiced', 'paid', 'rejected', 'cancelled'],
    enumName: 'estimates.estimate_status',
    nullable: true,
  })
  fromStatus: EstimateStatus | null;

  @Column({
    name: 'to_status',
    type: 'enum',
    enum: ['draft', 'submitted', 'reviewed', 'approved', 'invoiced', 'paid', 'rejected', 'cancelled'],
    enumName: 'estimates.estimate_status',
  })
  toStatus: EstimateStatus;

  @Column({ type: 'varchar', length: 50 })
  action: string;

  @Column({ type: 'text', nullable: true })
  comments: string | null;

  @Column({ name: 'performed_by', type: 'uuid' })
  performedById: string;

  @Column({ name: 'performed_at', type: 'timestamptz', default: () => 'NOW()' })
  performedAt: Date;

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

  @Column({ name: 'created_by', type: 'uuid', nullable: true })
  createdById: string | null;

  // Relations
  @ManyToOne(() => Tenant)
  @JoinColumn({ name: 'tenant_id' })
  tenant: Tenant;

  @ManyToOne(() => Estimacion, (e) => e.workflow)
  @JoinColumn({ name: 'estimacion_id' })
  estimacion: Estimacion;

  @ManyToOne(() => User)
  @JoinColumn({ name: 'performed_by' })
  performedBy: User;

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