import { MigrationInterface, QueryRunner } from 'typeorm';

export class CampaignCountryOrderReorderSeeder1783120000000 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      UPDATE campaign_category_country_order cco
      SET
        order_by = ranked.new_order_by,
        updated_at = CURRENT_TIMESTAMP
      FROM (
        SELECT
          cco2.id,
          ROW_NUMBER() OVER (
            PARTITION BY cco2.country_id, cc.category_id
            ORDER BY c.created_at ASC, c.id ASC
          ) AS new_order_by
        FROM campaign_category_country_order cco2
        INNER JOIN campaign_categories cc
          ON cc.id = cco2.campaign_category_id
         AND cc.deleted_at IS NULL
        INNER JOIN campaigns c
          ON c.id = cc.campaign_id
         AND c.deleted_at IS NULL
        WHERE cco2.deleted_at IS NULL
      ) ranked
      WHERE cco.id = ranked.id
        AND cco.order_by IS DISTINCT FROM ranked.new_order_by
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    // Data reorder migration; previous order_by values are not preserved.
  }
}
