import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { UomCategory } from './uom-category.entity';
import { Tenant } from './tenant.entity';

export enum UomType {
  REFERENCE = 'reference',
  BIGGER = 'bigger',
  SMALLER = 'smaller',
}

@Entity({ schema: 'core', name: 'uom' })
@Index('idx_uom_tenant', ['tenantId'])
@Index('idx_uom_category_id', ['categoryId'])
@Index('idx_uom_code', ['code'])
@Index('idx_uom_active', ['active'])
@Index('idx_uom_tenant_category_name', ['tenantId', 'categoryId', 'name'], { unique: true })
export class Uom {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

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

  @Column({ type: 'varchar', length: 100, nullable: false })
  name: string;

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

  @Column({
    type: 'enum',
    enum: UomType,
    nullable: false,
    default: UomType.REFERENCE,
    name: 'uom_type',
  })
  uomType: UomType;

  @Column({
    type: 'decimal',
    precision: 12,
    scale: 6,
    nullable: false,
    default: 1.0,
  })
  factor: number;

  @Column({
    type: 'decimal',
    precision: 12,
    scale: 6,
    nullable: true,
    default: 0.01,
  })
  rounding: number;

  @Column({ type: 'boolean', nullable: false, default: true })
  active: boolean;

  // Relations
  @ManyToOne(() => Tenant)
  @JoinColumn({ name: 'tenant_id' })
  tenant: Tenant;

  @ManyToOne(() => UomCategory, (category) => category.uoms, {
    nullable: false,
  })
  @JoinColumn({ name: 'category_id' })
  category: UomCategory;

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

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