import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  Index,
  ManyToOne,
  OneToMany,
  JoinColumn,
} from 'typeorm';
import { Warehouse } from './warehouse.entity.js';
import { StockQuant } from './stock-quant.entity.js';

export enum LocationType {
  INTERNAL = 'internal',
  SUPPLIER = 'supplier',
  CUSTOMER = 'customer',
  INVENTORY = 'inventory',
  PRODUCTION = 'production',
  TRANSIT = 'transit',
}

@Entity({ schema: 'inventory', name: 'locations' })
@Index('idx_locations_tenant_id', ['tenantId'])
@Index('idx_locations_warehouse_id', ['warehouseId'])
@Index('idx_locations_parent_id', ['parentId'])
@Index('idx_locations_type', ['locationType'])
export class Location {
  @PrimaryGeneratedColumn('uuid')
  id: string;

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

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

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

  @Column({ type: 'varchar', length: 500, nullable: true, name: 'complete_name' })
  completeName: string | null;

  @Column({
    type: 'enum',
    enum: LocationType,
    nullable: false,
    name: 'location_type',
  })
  locationType: LocationType;

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

  @Column({ type: 'boolean', default: false, nullable: false, name: 'is_scrap_location' })
  isScrapLocation: boolean;

  @Column({ type: 'boolean', default: false, nullable: false, name: 'is_return_location' })
  isReturnLocation: boolean;

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

  // Relations
  @ManyToOne(() => Warehouse, (warehouse) => warehouse.locations)
  @JoinColumn({ name: 'warehouse_id' })
  warehouse: Warehouse;

  @ManyToOne(() => Location, (location) => location.children)
  @JoinColumn({ name: 'parent_id' })
  parent: Location;

  @OneToMany(() => Location, (location) => location.parent)
  children: Location[];

  @OneToMany(() => StockQuant, (stockQuant) => stockQuant.location)
  stockQuants: StockQuant[];

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