import { MigrationInterface, QueryRunner } from 'typeorm';

export class ReplacePriorityRulesWithPriorityConfigs1783000000000 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      CREATE TABLE freight.priority_configs (
        id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
        type VARCHAR(20) NOT NULL CHECK (type IN ('WAGON', 'CURRENCY')),
        label VARCHAR(100) NOT NULL,
        currency VARCHAR(5) NULL,
        min_wagon_count INT NOT NULL,
        max_wagon_count INT NOT NULL,
        score_points INT NOT NULL DEFAULT 0,
        is_active BOOLEAN NOT NULL DEFAULT false,
        display_order INT NOT NULL DEFAULT 1,
        created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
        updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
        deleted_at TIMESTAMPTZ NULL,
        CONSTRAINT chk_wagon_range CHECK (min_wagon_count <= max_wagon_count),
        CONSTRAINT chk_currency_for_type CHECK (
          (type = 'WAGON' AND currency IS NULL) OR
          (type = 'CURRENCY' AND currency IS NOT NULL)
        )
      );
    `);

    await queryRunner.query(`
      CREATE INDEX idx_priority_configs_type_active ON freight.priority_configs (type, is_active);
    `);

    await queryRunner.query(`
      CREATE INDEX idx_priority_configs_currency_type ON freight.priority_configs (currency, type);
    `);
  }

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