/**
 * ComparativoProducto Entity
 * Productos cotizados por proveedor en comparativo
 *
 * @module Purchase
 * @table purchase.comparativo_productos
 * @ddl schemas/07-purchase-ext-schema-ddl.sql
 */

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { Tenant } from '../../core/entities/tenant.entity';
import { User } from '../../core/entities/user.entity';
import { ComparativoProveedor } from './comparativo-proveedor.entity';
import { Product } from '../../products/entities/product.entity';

@Entity({ schema: 'purchase', name: 'comparativo_productos' })
export class ComparativoProducto {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

  @Column({ name: 'comparativo_proveedor_id', type: 'uuid' })
  comparativoProveedorId: string;

  @Column({ name: 'product_id', type: 'uuid' })
  productId: string;

  @Column({ type: 'decimal', precision: 12, scale: 4 })
  quantity: number;

  @Column({ name: 'unit_price', type: 'decimal', precision: 12, scale: 4 })
  unitPrice: number;

  @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;

  // Computed property (in DB is GENERATED ALWAYS AS)
  get totalPrice(): number {
    return this.quantity * this.unitPrice;
  }

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

  @ManyToOne(() => ComparativoProveedor, (cp) => cp.productos, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'comparativo_proveedor_id' })
  comparativoProveedor: ComparativoProveedor;

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

  // FK a products.products (ERP-Core)
  @ManyToOne(() => Product, { nullable: false })
  @JoinColumn({ name: 'product_id' })
  product: Product;
}
