/**
 * CorrectiveAction Entity
 * Acciones correctivas (CAPA)
 *
 * @module Quality
 * @table quality.corrective_actions
 */

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  ManyToOne,
  JoinColumn,
  Index,
} from 'typeorm';
import { Tenant } from '../../core/entities/tenant.entity';
import { User } from '../../core/entities/user.entity';
import { NonConformity } from './non-conformity.entity';

export type ActionType = 'corrective' | 'preventive' | 'improvement';
export type ActionStatus = 'pending' | 'in_progress' | 'completed' | 'verified';

@Entity({ schema: 'construction', name: 'acciones_correctivas' })
@Index(['tenantId', 'nonConformityId'])
export class CorrectiveAction {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

  @Column({ name: 'no_conformidad_id', type: 'uuid' })
  nonConformityId: string;

  @Column({ name: 'action_type', type: 'varchar', length: 20 })
  actionType: ActionType;

  @Column({ type: 'text' })
  description: string;

  @Column({ name: 'responsible_id', type: 'uuid' })
  responsibleId: string;

  @Column({ name: 'due_date', type: 'date' })
  dueDate: Date;

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

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

  @Column({ name: 'completion_notes', type: 'text', nullable: true })
  completionNotes: string;

  @Column({ name: 'verified_at', type: 'timestamptz', nullable: true })
  verifiedAt: Date;

  @Column({ name: 'verified_by', type: 'uuid', nullable: true })
  verifiedById: string;

  @Column({ name: 'effectiveness_verified', type: 'boolean', default: false })
  effectivenessVerified: boolean;

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

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

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

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

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

  @ManyToOne(() => NonConformity, (nc) => nc.correctiveActions, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'no_conformidad_id' })
  nonConformity: NonConformity;

  @ManyToOne(() => User)
  @JoinColumn({ name: 'responsible_id' })
  responsible: User;

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

  @ManyToOne(() => User)
  @JoinColumn({ name: 'verified_by' })
  verifiedBy: User;
}
