/**
 * InvoiceItem Entity
 * Line items for unified invoices
 * Compatible with erp-core invoice-item.entity
 *
 * @module Invoices
 */

import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { Invoice } from './invoice.entity';

@Entity({ name: 'invoice_items', schema: 'billing' })
export class InvoiceItem {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Index()
  @Column({ name: 'invoice_id', type: 'uuid' })
  invoiceId: string;

  @ManyToOne(() => Invoice, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'invoice_id' })
  invoice: Invoice;

  @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;

  // SAT (Mexico)
  @Column({ name: 'sat_product_code', type: 'varchar', length: 20, nullable: true })
  satProductCode?: string;

  @Column({ name: 'sat_unit_code', type: 'varchar', length: 10, nullable: true })
  satUnitCode?: string;

  @Column({ type: 'decimal', precision: 15, scale: 4, default: 1 })
  quantity: 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({ name: 'withholding_rate', type: 'decimal', precision: 5, scale: 2, default: 0 })
  withholdingRate: number;

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

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

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

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

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