import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn, UpdateDateColumn, Index, ManyToOne, JoinColumn } from 'typeorm';
import { SalesOrder } from './sales-order.entity';

@Entity({ name: 'sales_order_items', schema: 'sales' })
export class SalesOrderItem {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Index()
  @Column({ name: 'order_id', type: 'uuid' })
  orderId: string;

  @ManyToOne(() => SalesOrder, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'order_id' })
  order: SalesOrder;

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

  @Column({ name: 'line_number', type: 'int', default: 1 })
  lineNumber: number;

  @Column({ name: 'product_sku', type: 'varchar', length: 50, nullable: true })
  productSku?: string;

  @Column({ name: 'product_name', type: 'varchar', length: 200 })
  productName: string;

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

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

  @Column({ name: 'quantity_reserved', type: 'decimal', precision: 15, scale: 4, default: 0 })
  quantityReserved: number;

  @Column({ name: 'quantity_shipped', type: 'decimal', precision: 15, scale: 4, default: 0 })
  quantityShipped: number;

  @Column({ name: 'quantity_delivered', type: 'decimal', precision: 15, scale: 4, default: 0 })
  quantityDelivered: number;

  @Column({ name: 'quantity_returned', type: 'decimal', precision: 15, scale: 4, default: 0 })
  quantityReturned: number;

  @Column({ type: 'varchar', length: 20, default: 'PZA' })
  uom: string;

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

  @Column({ name: 'unit_cost', type: 'decimal', precision: 15, scale: 4, default: 0 })
  unitCost: number;

  @Column({ name: 'discount_percent', type: 'decimal', precision: 5, scale: 2, default: 0 })
  discountPercent: number;

  @Column({ name: 'discount_amount', type: 'decimal', precision: 15, scale: 2, default: 0 })
  discountAmount: number;

  @Column({ name: 'tax_rate', type: 'decimal', precision: 5, scale: 2, default: 16.00 })
  taxRate: number;

  @Column({ name: 'tax_amount', type: 'decimal', precision: 15, scale: 2, default: 0 })
  taxAmount: number;

  @Column({ type: 'decimal', precision: 15, scale: 2, default: 0 })
  subtotal: number;

  @Column({ type: 'decimal', precision: 15, scale: 2, default: 0 })
  total: number;

  @Column({ name: 'lot_number', type: 'varchar', length: 50, nullable: true })
  lotNumber?: string;

  @Column({ name: 'serial_number', type: 'varchar', length: 50, nullable: true })
  serialNumber?: string;

  @Index()
  @Column({ type: 'varchar', length: 20, default: 'pending' })
  status: 'pending' | 'reserved' | 'shipped' | 'delivered' | 'cancelled';

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

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