import {
  Column,
  CreateDateColumn,
  Entity,
  Index,
  JoinColumn,
  ManyToOne,
  OneToMany,
  PrimaryGeneratedColumn,
  UpdateDateColumn,
} from "typeorm";
import { OrdenTrabajo } from "../../ots/entities/orden-trabajo.entity";
import { CotizacionLinea } from "./cotizacion-linea.entity";

export enum EstadoCotizacion {
  BORRADOR = "borrador",
  ENVIADA = "enviada",
  APROBADA = "aprobada",
  RECHAZADA = "rechazada",
}

@Entity("taller_cotizaciones")
export class Cotizacion {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ name: "ot_id" })
  @Index()
  otId: number;

  @ManyToOne(() => OrdenTrabajo, (ot) => ot.cotizaciones, {
    onDelete: "CASCADE",
  })
  @JoinColumn({ name: "ot_id" })
  ordenTrabajo: OrdenTrabajo;

  @Column({ name: "numero_cotizacion", length: 20, nullable: true })
  numeroCotizacion: string; // COT-YYYYMMDD-XXXX

  @Column({ type: "decimal", precision: 12, scale: 2, default: 0 })
  subtotal: number;

  @Column({ type: "decimal", precision: 12, scale: 2, default: 0 })
  iva: number;

  @Column({ type: "decimal", precision: 12, scale: 2, default: 0 })
  total: number;

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

  @Column({ name: "fecha_aprobacion", type: "datetime", nullable: true })
  fechaAprobacion: Date;

  @Column({ name: "aprobado_por", length: 255, nullable: true })
  aprobadoPor: string;

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

  @Column({ name: "local_id", length: 36, nullable: true })
  localId: string;

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

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

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

  // Relations
  @OneToMany(() => CotizacionLinea, (linea) => linea.cotizacion, {
    cascade: true,
    eager: true,
  })
  lineas: CotizacionLinea[];
}
