import { MigrationInterface, QueryRunner, Table, TableColumn } from 'typeorm';

/**
 * Batch 5 — warehouse allocation rules, storage/demurrage fee rules,
 * and demurrage lifecycle timestamps on inventory. Idempotent.
 */
export class AddWarehouseAllocationAndFeeRules1791000000000 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.createTable(
      new Table({
        schema: 'freight',
        name: 'warehouse_allocation_rules',
        columns: [
          { name: 'id', type: 'uuid', isPrimary: true, default: 'uuid_generate_v4()' },
          { name: 'name', type: 'varchar', length: '160' },
          { name: 'priority', type: 'int', default: 100 },
          { name: 'freight_type', type: 'varchar', length: '16', isNullable: true },
          { name: 'trade_direction', type: 'varchar', length: '16', isNullable: true },
          { name: 'cargo_type_code', type: 'varchar', length: '50', isNullable: true },
          { name: 'container_status', type: 'varchar', length: '24', isNullable: true },
          { name: 'requires_inspection', type: 'boolean', isNullable: true },
          { name: 'target_facility_code', type: 'varchar', length: '40', isNullable: true },
          { name: 'target_yard_code', type: 'varchar', length: '40' },
          { name: 'target_warehouse_code', type: 'varchar', length: '40', isNullable: true },
          { name: 'target_zone_code', type: 'varchar', length: '40', isNullable: true },
          { name: 'storage_type', type: 'varchar', length: '80', isNullable: true },
          { name: 'is_active', type: 'boolean', default: true },
          { name: 'created_at', type: 'timestamptz', default: 'now()' },
          { name: 'updated_at', type: 'timestamptz', default: 'now()' },
          { name: 'deleted_at', type: 'timestamptz', isNullable: true },
        ],
        indices: [
          { name: 'idx_war_priority', columnNames: ['priority'] },
          { name: 'idx_war_active', columnNames: ['is_active'] },
        ],
      }),
      true,
    );

    await queryRunner.createTable(
      new Table({
        schema: 'freight',
        name: 'warehouse_fee_rules',
        columns: [
          { name: 'id', type: 'uuid', isPrimary: true, default: 'uuid_generate_v4()' },
          { name: 'name', type: 'varchar', length: '160' },
          { name: 'rule_type', type: 'varchar', length: '20' },
          { name: 'priority', type: 'int', default: 100 },
          { name: 'freight_type', type: 'varchar', length: '16', isNullable: true },
          { name: 'trade_direction', type: 'varchar', length: '16', isNullable: true },
          { name: 'cargo_type_code', type: 'varchar', length: '50', isNullable: true },
          { name: 'container_type', type: 'varchar', length: '40', isNullable: true },
          { name: 'facility_id', type: 'uuid', isNullable: true },
          { name: 'warehouse_id', type: 'uuid', isNullable: true },
          { name: 'yard_id', type: 'uuid', isNullable: true },
          { name: 'zone_id', type: 'uuid', isNullable: true },
          { name: 'free_days', type: 'int', default: 0 },
          { name: 'rate_per_day', type: 'numeric', precision: 14, scale: 2, default: 0 },
          { name: 'currency', type: 'varchar', length: '8', default: "'USD'" },
          { name: 'is_active', type: 'boolean', default: true },
          { name: 'created_at', type: 'timestamptz', default: 'now()' },
          { name: 'updated_at', type: 'timestamptz', default: 'now()' },
          { name: 'deleted_at', type: 'timestamptz', isNullable: true },
        ],
        indices: [
          { name: 'idx_wfr_type', columnNames: ['rule_type'] },
          { name: 'idx_wfr_active', columnNames: ['is_active'] },
        ],
      }),
      true,
    );

    const inventoryTable = await queryRunner.getTable('freight.warehouse_inventory');
    if (inventoryTable) {
      const columnsToAdd = [
        { name: 'inspection_started_at', type: 'timestamptz', isNullable: true },
        { name: 'inspection_completed_at', type: 'timestamptz', isNullable: true },
        { name: 'ready_for_pickup_at', type: 'timestamptz', isNullable: true },
        { name: 'release_date', type: 'timestamptz', isNullable: true },
        { name: 'gate_cleared_at', type: 'timestamptz', isNullable: true },
      ];

      const columnsToCreate = columnsToAdd.filter(
        (col) => !inventoryTable.columns.some((c) => c.name === col.name),
      );

      if (columnsToCreate.length > 0) {
        await queryRunner.addColumns(
          'freight.warehouse_inventory',
          columnsToCreate.map((col) => new TableColumn(col)),
        );
      }
    }
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    const inventoryTable = await queryRunner.getTable('freight.warehouse_inventory');
    if (inventoryTable) {
      const columnNames = [
        'inspection_started_at',
        'inspection_completed_at',
        'ready_for_pickup_at',
        'release_date',
        'gate_cleared_at',
      ];
      const columnsToRemove = columnNames.filter((name) =>
        inventoryTable.columns.some((c) => c.name === name),
      );

      if (columnsToRemove.length > 0) {
        await queryRunner.dropColumns('freight.warehouse_inventory', columnsToRemove);
      }
    }

    const feeRulesTable = await queryRunner.getTable('freight.warehouse_fee_rules');
    if (feeRulesTable) {
      await queryRunner.dropTable('freight.warehouse_fee_rules', true);
    }

    const allocationRulesTable = await queryRunner.getTable('freight.warehouse_allocation_rules');
    if (allocationRulesTable) {
      await queryRunner.dropTable('freight.warehouse_allocation_rules', true);
    }
  }
}
