import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  Index,
  ManyToOne,
  OneToMany,
  JoinColumn,
} from 'typeorm';
import { PurchaseOrderMatching } from './purchase-order-matching.entity';
import { MatchingException } from './matching-exception.entity';

export type MatchingLineStatus = 'pending' | 'partial' | 'matched' | 'mismatch';

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

  @Index()
  @Column({ name: 'matching_id', type: 'uuid' })
  matchingId: string;

  @ManyToOne(() => PurchaseOrderMatching, (matching) => matching.lines, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'matching_id' })
  matching: PurchaseOrderMatching;

  @Index()
  @Column({ name: 'order_item_id', type: 'uuid' })
  orderItemId: string;

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

  // Quantities
  @Column({ name: 'qty_ordered', type: 'decimal', precision: 15, scale: 4 })
  qtyOrdered: number;

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

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

  // Prices
  @Column({ name: 'price_ordered', type: 'decimal', precision: 15, scale: 2 })
  priceOrdered: number;

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

  // Generated columns (read-only in TypeORM)
  @Column({
    name: 'qty_variance',
    type: 'decimal',
    precision: 15,
    scale: 4,
    insert: false,
    update: false,
    nullable: true,
  })
  qtyVariance: number;

  @Column({
    name: 'invoice_qty_variance',
    type: 'decimal',
    precision: 15,
    scale: 4,
    insert: false,
    update: false,
    nullable: true,
  })
  invoiceQtyVariance: number;

  @Column({
    name: 'price_variance',
    type: 'decimal',
    precision: 15,
    scale: 2,
    insert: false,
    update: false,
    nullable: true,
  })
  priceVariance: number;

  @Index()
  @Column({ type: 'varchar', length: 20, default: 'pending' })
  status: MatchingLineStatus;

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

  // Relations
  @OneToMany(() => MatchingException, (exception) => exception.matchingLine)
  exceptions: MatchingException[];
}
