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

@Entity({ name: 'purchase_order_items', schema: 'purchases' })
export class PurchaseOrderItem {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

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

  @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({ name: 'supplier_sku', type: 'varchar', length: 50, nullable: true })
  supplierSku?: string;

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

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

  @Column({ name: 'quantity_received', type: 'decimal', precision: 15, scale: 4, default: 0 })
  quantityReceived: 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: '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: 'expiry_date', type: 'date', nullable: true })
  expiryDate?: Date;

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

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

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