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

@Entity({ schema: 'inventory', name: 'inventory_adjustment_lines' })
@Index('idx_adjustment_lines_adjustment_id', ['adjustmentId'])
@Index('idx_adjustment_lines_product_id', ['productId'])
export class InventoryAdjustmentLine {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ type: 'uuid', nullable: false, name: 'adjustment_id' })
  adjustmentId: 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, name: 'theoretical_qty' })
  theoreticalQty: number;

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

  @Column({
    type: 'decimal',
    precision: 16,
    scale: 4,
    nullable: false,
    name: 'difference_qty',
    generated: 'STORED',
    asExpression: 'counted_qty - theoretical_qty',
  })
  differenceQty: number;

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

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

  // Relations
  @ManyToOne(() => InventoryAdjustment, (adjustment) => adjustment.lines, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'adjustment_id' })
  adjustment: InventoryAdjustment;

  @ManyToOne(() => Product)
  @JoinColumn({ name: 'product_id' })
  product: Product;

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

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

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