import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { Product } from './product.entity.js';
import { Company } from '../../auth/entities/company.entity.js';

@Entity({ schema: 'inventory', name: 'stock_valuation_layers' })
@Index('idx_valuation_layers_tenant_id', ['tenantId'])
@Index('idx_valuation_layers_product_id', ['productId'])
@Index('idx_valuation_layers_company_id', ['companyId'])
@Index('idx_valuation_layers_stock_move_id', ['stockMoveId'])
@Index('idx_valuation_layers_remaining_qty', ['remainingQty'])
export class StockValuationLayer {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

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

  @Column({ type: 'uuid', nullable: false, name: 'company_id' })
  companyId: string;

  @Column({ type: 'decimal', precision: 16, scale: 4, nullable: false })
  quantity: number;

  @Column({ type: 'decimal', precision: 12, scale: 2, nullable: false, name: 'unit_cost' })
  unitCost: number;

  @Column({ type: 'decimal', precision: 16, scale: 2, nullable: false })
  value: number;

  @Column({ type: 'decimal', precision: 16, scale: 4, nullable: false, name: 'remaining_qty' })
  remainingQty: number;

  @Column({ type: 'decimal', precision: 16, scale: 2, nullable: false, name: 'remaining_value' })
  remainingValue: number;

  @Column({ type: 'uuid', nullable: true, name: 'stock_move_id' })
  stockMoveId: string | null;

  @Column({ type: 'varchar', length: 255, nullable: true })
  description: string | null;

  @Column({ type: 'uuid', nullable: true, name: 'account_move_id' })
  accountMoveId: string | null;

  @Column({ type: 'uuid', nullable: true, name: 'journal_entry_id' })
  journalEntryId: string | null;

  // Relations
  @ManyToOne(() => Product)
  @JoinColumn({ name: 'product_id' })
  product: Product;

  @ManyToOne(() => Company)
  @JoinColumn({ name: 'company_id' })
  company: Company;

  // Auditoría
  @CreateDateColumn({ name: 'created_at', type: 'timestamp' })
  createdAt: Date;

  @Column({ type: 'uuid', nullable: true, name: 'created_by' })
  createdBy: string | null;

  @UpdateDateColumn({
    name: 'updated_at',
    type: 'timestamp',
    nullable: true,
  })
  updatedAt: Date | null;

  @Column({ type: 'uuid', nullable: true, name: 'updated_by' })
  updatedBy: string | null;
}
