import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  ManyToOne,
  JoinColumn,
} from 'typeorm';
import { Picking } from './picking.entity.js';
import { Product } from './product.entity.js';
import { Location } from './location.entity.js';
import { Lot } from './lot.entity.js';
import { MoveStatus } from './enums.js';

@Entity({ schema: 'inventory', name: 'stock_moves' })
@Index('idx_stock_moves_tenant_id', ['tenantId'])
@Index('idx_stock_moves_picking_id', ['pickingId'])
@Index('idx_stock_moves_product_id', ['productId'])
@Index('idx_stock_moves_status', ['status'])
@Index('idx_stock_moves_date', ['date'])
export class StockMove {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

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

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

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

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

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

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

  @Column({ type: 'decimal', precision: 16, scale: 4, default: 0, name: 'quantity_done' })
  quantityDone: number;

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

  @Column({
    type: 'enum',
    enum: MoveStatus,
    default: MoveStatus.DRAFT,
    nullable: false,
  })
  status: MoveStatus;

  @Column({ type: 'timestamp', nullable: true })
  date: Date | null;

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

  // Relations
  @ManyToOne(() => Picking, (picking) => picking.moves, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'picking_id' })
  picking: Picking;

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

  @ManyToOne(() => Location)
  @JoinColumn({ name: 'location_id' })
  location: Location;

  @ManyToOne(() => Location)
  @JoinColumn({ name: 'location_dest_id' })
  locationDest: Location;

  @ManyToOne(() => Lot, { nullable: true })
  @JoinColumn({ name: 'lot_id' })
  lot: Lot | null;

  // 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;
}
