// Entity representing the external ERP cliente table (maecli)
// This is read from the ERP database, not managed by TypeORM
import { AfterLoad, Column, Entity, Index, PrimaryColumn } from "typeorm";

@Entity("maecli")
export class Cliente {
  @PrimaryColumn({ length: 24 })
  @Index()
  tarjeta: string;

  @Column({ length: 255 })
  nombre: string;

  @Column({ length: 255 })
  direccion: string;

  @Column({ length: 48, nullable: true })
  telefono: string;

  @Column({ length: 10, nullable: true })
  celular: string;

  @Column({ length: 24 })
  @Index()
  nit: string;

  @Column({ length: 255, nullable: true })
  email: string;

  @Column({ length: 255, nullable: true })
  comercial: string;

  @Column({ length: 255, nullable: true })
  razonsocial: string;

  // Additional fields from maecli that might be useful
  @Column({ nullable: true })
  id: number;

  @AfterLoad()
  computeDisplayName() {
    // Logic to determine best name:
    // 1. If nombre is empty or matches NIT/Tarjeta, try comercial/razonsocial
    // 2. Normalize inputs
    const nombre = (this.nombre || "").trim();
    const nit = (this.nit || "").trim();
    const tarjeta = (this.tarjeta || "").trim();
    const comercial = (this.comercial || "").trim();
    const razonsocial = (this.razonsocial || "").trim();

    // Heuristic: If nombre looks like NIT/ID (digits/dashes only) or is empty
    const isNombreInvalid =
      !nombre ||
      nombre === nit ||
      nombre === tarjeta ||
      /^[\d-]+$/.test(nombre);

    if (isNombreInvalid) {
      if (comercial) {
        this.nombre = comercial;
      } else if (razonsocial) {
        this.nombre = razonsocial;
      }
    }
  }
}
