import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
  Unique,
} from 'typeorm';
import { Product } from './product.entity.js';
import { Location } from './location.entity.js';
import { Lot } from './lot.entity.js';

@Entity({ schema: 'inventory', name: 'stock_quants' })
@Index('idx_stock_quants_product_id', ['productId'])
@Index('idx_stock_quants_location_id', ['locationId'])
@Index('idx_stock_quants_lot_id', ['lotId'])
@Unique('uq_stock_quants_product_location_lot', ['productId', 'locationId', 'lotId'])
export class StockQuant {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

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

  @Column({ type: 'uuid', nullable: false, name: 'location_id' })
  locationId: string;

  @Column({ type: 'uuid', nullable: true, name: 'lot_id' })
  lotId: string | null;

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

  @Column({ type: 'decimal', precision: 16, scale: 4, default: 0, name: 'reserved_quantity' })
  reservedQuantity: number;

  // Relations
  @ManyToOne(() => Product, (product) => product.stockQuants)
  @JoinColumn({ name: 'product_id' })
  product: Product;

  @ManyToOne(() => Location, (location) => location.stockQuants)
  @JoinColumn({ name: 'location_id' })
  location: Location;

  @ManyToOne(() => Lot, (lot) => lot.stockQuants, { nullable: true })
  @JoinColumn({ name: 'lot_id' })
  lot: Lot | null;

  // Auditoría
  @CreateDateColumn({ name: 'created_at', type: 'timestamp' })
  createdAt: Date;

  @UpdateDateColumn({
    name: 'updated_at',
    type: 'timestamp',
    nullable: true,
  })
  updatedAt: Date | null;
}
