import {
  Column,
  CreateDateColumn,
  Entity,
  Index,
  JoinColumn,
  ManyToOne,
  OneToMany,
  OneToOne,
  PrimaryGeneratedColumn,
  UpdateDateColumn,
} from "typeorm";
import { Cotizacion } from "../../cotizaciones/entities/cotizacion.entity";
import { Vehiculo } from "../../vehiculos/entities/vehiculo.entity";
import { OtCosaTrae } from "./ot-cosa-trae.entity";
import { OtDano } from "./ot-dano.entity";
import { OtFirma } from "./ot-firma.entity";
import { OtFoto } from "./ot-foto.entity";

export enum EstadoOT {
  BORRADOR = "borrador",
  EN_PROCESO = "en_proceso",
  COTIZADA = "cotizada",
  APROBADA = "aprobada",
  TERMINADA = "terminada",
  ENTREGADA = "entregada",
}

@Entity("taller_ordenes_trabajo")
export class OrdenTrabajo {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ name: "numero_ot", length: 20, unique: true })
  @Index()
  numeroOt: string;

  @Column({ name: "cliente_tarjeta", length: 24 })
  @Index()
  clienteTarjeta: string; // FK a maecli.tarjeta

  @Column({ name: "vehiculo_id" })
  vehiculoId: number;

  @ManyToOne(() => Vehiculo)
  @JoinColumn({ name: "vehiculo_id" })
  vehiculo: Vehiculo;

  @Column({ name: "fecha_entrada", type: "datetime" })
  @Index()
  fechaEntrada: Date;

  @Column({ name: "fecha_salida", type: "datetime", nullable: true })
  @Index()
  fechaSalida: Date;

  @Column()
  km: number;

  @Column({ name: "nivel_gasolina", default: 0 })
  nivelGasolina: number; // 0-100

  @Column({ name: "requerimiento_cliente", type: "text", nullable: true })
  requerimientoCliente: string;

  @Column({ type: "text", nullable: true })
  observaciones: string;

  @Column({
    type: "enum",
    enum: EstadoOT,
    default: EstadoOT.BORRADOR,
  })
  @Index()
  estado: EstadoOT;

  @Column({ name: "pdf_escaner", length: 500, nullable: true })
  pdfEscaner: string;

  @Column({ name: "local_id", length: 36, nullable: true })
  @Index()
  localId: string; // UUID para sync offline

  @Column({ default: 1 })
  version: number;

  @CreateDateColumn({ name: "created_at" })
  createdAt: Date;

  @UpdateDateColumn({ name: "updated_at" })
  updatedAt: Date;

  @Column({ name: "created_by", type: "int", nullable: true })
  createdBy: number | null;

  @Column({ name: "updated_by", type: "int", nullable: true })
  updatedBy: number | null;

  // Relations
  @OneToMany(() => OtCosaTrae, (ct) => ct.ordenTrabajo, { cascade: true })
  cosasTrae: OtCosaTrae[];

  @OneToMany(() => OtDano, (d) => d.ordenTrabajo, { cascade: true })
  danos: OtDano[];

  @OneToMany(() => OtFoto, (f) => f.ordenTrabajo, { cascade: true })
  fotos: OtFoto[];

  @OneToOne(() => OtFirma, (f) => f.ordenTrabajo, { cascade: true })
  firma: OtFirma;

  @OneToMany(() => Cotizacion, (c) => c.ordenTrabajo, { cascade: true })
  cotizaciones: Cotizacion[];
}
