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({ name: "asesor_id", type: "int", nullable: true })
  asesorId: number | null;

  @Column({ name: "asesor_nombre", type: "varchar", length: 255, nullable: true })
  asesorNombre: string | null;

  @Column({ name: "public_token", type: "varchar", length: 64, nullable: true, unique: true })
  @Index()
  publicToken: string | null;

  @Column({ name: "public_expires_at", type: "datetime", nullable: true })
  publicExpiresAt: Date | null;

  @Column({ name: "decision_cliente_at", type: "datetime", nullable: true })
  decisionClienteAt: Date | null;

  @Column({ name: "decision_cliente_nombre", type: "varchar", length: 255, nullable: true })
  decisionClienteNombre: string | null;

  // mediumtext (16MB), no text (65KB): PublicDecisionDto.firma acepta data
  // URLs de hasta 1.5MB (ver validatePublicSignature en el service) y el pad
  // de firma dibuja al devicePixelRatio real del telefono (signature-pad.ts),
  // asi que una firma real con trazo cargado supera los 65KB de un TEXT sin
  // que ninguna validacion de la app lo atrape -- el INSERT fallaba en MySQL
  // con ER_DATA_TOO_LONG, sin filtro de excepciones que lo tradujera, y el
  // cliente veia un 500 "Internal server error" crudo al aceptar la cotizacion.
  @Column({ name: "decision_cliente_firma", type: "mediumtext", nullable: true })
  decisionClienteFirma: string | null;

  @Column({ name: "decision_cliente_motivo", type: "text", nullable: true })
  decisionClienteMotivo: string | null;

  @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[];
}
