import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Batch 3 — Warehouse → Loading → Train Departure visibility.
 * Adds the warehouse_loadings record (inventory ↔ wagon). Does NOT touch any
 * scheduling / wagon tables — the warehouse only reads from those.
 */
export class WarehouseBatch31790000000002 implements MigrationInterface {
  name = 'WarehouseBatch31790000000002';

  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE IF NOT EXISTS freight.warehouse_loadings (
        id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
        warehouse_inventory_id UUID NOT NULL REFERENCES freight.warehouse_inventory(id) ON DELETE CASCADE,
        booking_id UUID NULL,
        wagon_id UUID NOT NULL,
        loaded_at TIMESTAMPTZ NOT NULL DEFAULT now(),
        loaded_by VARCHAR(120) NULL,
        loaded_weight NUMERIC(14,3) NULL,
        notes TEXT NULL,
        created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
        updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
        deleted_at TIMESTAMPTZ NULL
      );
    `);
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS idx_warehouse_loadings_inventory_id
      ON freight.warehouse_loadings(warehouse_inventory_id);
    `);
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS idx_warehouse_loadings_booking_id
      ON freight.warehouse_loadings(booking_id);
    `);
    await queryRunner.query(`
      CREATE INDEX IF NOT EXISTS idx_warehouse_loadings_wagon_id
      ON freight.warehouse_loadings(wagon_id);
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`DROP TABLE IF EXISTS freight.warehouse_loadings;`);
  }
}
