import { MigrationInterface, QueryRunner } from 'typeorm';

/**
 * Weights are tonnes everywhere. Warehouse / yard / zone capacity was stored in
 * kg (e.g. 25000, 5000, 2500) — convert existing rows to tonnes (÷1000). Cargo
 * weight (warehouse_inventory.weight ← cargo_total_weight_vgm) is already tonnes
 * and is NOT touched; truck gross weight has no data yet. Runs exactly once
 * (tracked by TypeORM) — re-running would divide again.
 */
export class WarehouseCapacityKgToTons2020000000000 implements MigrationInterface {
  name = 'WarehouseCapacityKgToTons2020000000000';

  private readonly tables = ['warehouses', 'warehouse_yards', 'warehouse_zones'];
  private readonly columns = ['capacity_weight', 'current_weight', 'max_weight'];

  public async up(queryRunner: QueryRunner): Promise<void> {
    for (const table of this.tables) {
      for (const column of this.columns) {
        await queryRunner.query(
          `UPDATE freight.${table} SET ${column} = ${column} / 1000.0 WHERE ${column} IS NOT NULL`,
        );
      }
    }
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    for (const table of this.tables) {
      for (const column of this.columns) {
        await queryRunner.query(
          `UPDATE freight.${table} SET ${column} = ${column} * 1000.0 WHERE ${column} IS NOT NULL`,
        );
      }
    }
  }
}
