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

export type ExceptionType =
  | 'over_receipt'
  | 'short_receipt'
  | 'over_invoice'
  | 'short_invoice'
  | 'price_variance';

export type ExceptionStatus = 'pending' | 'approved' | 'rejected';

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

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

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

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

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

  @ManyToOne(() => PurchaseMatchingLine, (line) => line.exceptions, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'matching_line_id' })
  matchingLine?: PurchaseMatchingLine;

  @Index()
  @Column({ name: 'exception_type', type: 'varchar', length: 50 })
  exceptionType: ExceptionType;

  @Column({ name: 'expected_value', type: 'decimal', precision: 15, scale: 4, nullable: true })
  expectedValue?: number;

  @Column({ name: 'actual_value', type: 'decimal', precision: 15, scale: 4, nullable: true })
  actualValue?: number;

  @Column({ name: 'variance_value', type: 'decimal', precision: 15, scale: 4, nullable: true })
  varianceValue?: number;

  @Column({ name: 'variance_percent', type: 'decimal', precision: 5, scale: 2, nullable: true })
  variancePercent?: number;

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

  @Column({ name: 'resolved_at', type: 'timestamptz', nullable: true })
  resolvedAt?: Date;

  @Column({ name: 'resolved_by', type: 'uuid', nullable: true })
  resolvedBy?: string;

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

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