/**
 * ComparativoCotizaciones Entity
 * Cuadro comparativo de cotizaciones
 *
 * @module Purchase
 * @table purchase.comparativo_cotizaciones
 * @ddl schemas/07-purchase-ext-schema-ddl.sql
 */

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  ManyToOne,
  OneToMany,
  JoinColumn,
  Index,
} from 'typeorm';
import { Tenant } from '../../core/entities/tenant.entity';
import { User } from '../../core/entities/user.entity';
import { RequisicionObra } from '../../inventory/entities/requisicion-obra.entity';
import { ComparativoProveedor } from './comparativo-proveedor.entity';
import { Partner } from '../../partners/entities/partner.entity';

export type ComparativoStatus = 'draft' | 'in_evaluation' | 'approved' | 'cancelled';

@Entity({ schema: 'purchase', name: 'comparativo_cotizaciones' })
@Index(['tenantId', 'code'], { unique: true })
export class ComparativoCotizaciones {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

  @Column({ name: 'requisicion_id', type: 'uuid', nullable: true })
  requisicionId: string;

  @Column({ type: 'varchar', length: 30 })
  code: string;

  @Column({ type: 'varchar', length: 255 })
  name: string;

  @Column({ name: 'comparison_date', type: 'date' })
  comparisonDate: Date;

  @Column({ type: 'varchar', length: 20, default: 'draft' })
  status: ComparativoStatus;

  @Column({ name: 'winner_supplier_id', type: 'uuid', nullable: true })
  winnerSupplierId: string;

  @Column({ name: 'approved_by', type: 'uuid', nullable: true })
  approvedById: string;

  @Column({ name: 'approved_at', type: 'timestamptz', nullable: true })
  approvedAt: Date;

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

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

  @Column({ name: 'created_by', type: 'uuid', nullable: true })
  createdById: string;

  @UpdateDateColumn({ name: 'updated_at', type: 'timestamptz' })
  updatedAt: Date;

  @Column({ name: 'updated_by', type: 'uuid', nullable: true })
  updatedById: string;

  @Column({ name: 'deleted_at', type: 'timestamptz', nullable: true })
  deletedAt: Date;

  @Column({ name: 'deleted_by', type: 'uuid', nullable: true })
  deletedById: string;

  // Relations
  @ManyToOne(() => Tenant)
  @JoinColumn({ name: 'tenant_id' })
  tenant: Tenant;

  @ManyToOne(() => RequisicionObra)
  @JoinColumn({ name: 'requisicion_id' })
  requisicion: RequisicionObra;

  @ManyToOne(() => User)
  @JoinColumn({ name: 'approved_by' })
  approvedBy: User;

  @ManyToOne(() => User)
  @JoinColumn({ name: 'created_by' })
  createdBy: User;

  @OneToMany(() => ComparativoProveedor, (cp) => cp.comparativo)
  proveedores: ComparativoProveedor[];

  // FK a partners.partners (ERP-Core) - proveedor ganador
  @ManyToOne(() => Partner, { nullable: true })
  @JoinColumn({ name: 'winner_supplier_id' })
  winnerSupplier: Partner;
}
