/**
 * MaintenanceHistory Entity - Historial de Mantenimientos
 *
 * Registro historico de todos los mantenimientos realizados.
 *
 * @module Assets (MAE-015)
 */

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  ManyToOne,
  JoinColumn,
  Index,
} from 'typeorm';
import { Asset } from './asset.entity';
import { WorkOrder } from './work-order.entity';

@Entity('maintenance_history', { schema: 'assets' })
@Index(['tenantId', 'assetId'])
@Index(['tenantId', 'maintenanceDate'])
export class MaintenanceHistory {
  @PrimaryGeneratedColumn('uuid')
  id!: string;

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

  // Activo
  @Column({ name: 'asset_id', type: 'uuid' })
  assetId!: string;

  @ManyToOne(() => Asset, (asset) => asset.maintenanceHistory)
  @JoinColumn({ name: 'asset_id' })
  asset!: Asset;

  // Orden de trabajo (si aplica)
  @Column({ name: 'work_order_id', type: 'uuid', nullable: true })
  workOrderId?: string;

  @ManyToOne(() => WorkOrder, { nullable: true })
  @JoinColumn({ name: 'work_order_id' })
  workOrder?: WorkOrder;

  // Fecha y tipo
  @Column({ name: 'maintenance_date', type: 'date' })
  maintenanceDate!: Date;

  @Column({
    name: 'maintenance_type',
    type: 'enum',
    enum: ['preventive', 'corrective', 'predictive', 'emergency'],
    enumName: 'maintenance_type',
  })
  maintenanceType!: string;

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

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

  // Metricas al momento del mantenimiento
  @Column({ name: 'hours_at_maintenance', type: 'decimal', precision: 12, scale: 2, nullable: true })
  hoursAtMaintenance?: number;

  @Column({ name: 'kilometers_at_maintenance', type: 'decimal', precision: 12, scale: 2, nullable: true })
  kilometersAtMaintenance?: number;

  // Costos
  @Column({ name: 'labor_cost', type: 'decimal', precision: 18, scale: 2, default: 0 })
  laborCost!: number;

  @Column({ name: 'parts_cost', type: 'decimal', precision: 18, scale: 2, default: 0 })
  partsCost!: number;

  @Column({ name: 'total_cost', type: 'decimal', precision: 18, scale: 2, default: 0 })
  totalCost!: number;

  // Ejecutor
  @Column({ name: 'performed_by_id', type: 'uuid', nullable: true })
  performedById?: string;

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

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

  // Documentos
  @Column({ type: 'jsonb', nullable: true })
  documents?: string[];

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

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

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