import { MigrationInterface, QueryRunner } from 'typeorm';

export class AllCategoryCountryRecommendedSeeder1782711473128 implements MigrationInterface {
  public async up(queryRunner: QueryRunner): Promise<void> {
    const allCategory = await queryRunner.query(`
      SELECT category_id
      FROM category_translations
      WHERE slug = 'all'
        AND language_code = 'en'
        AND deleted_at IS NULL
      LIMIT 1
    `);

    if (!allCategory.length) {
      throw new Error(
        'All category not found. Ensure AllCategorySeeder migration has run first.',
      );
    }

    const allCategoryId = allCategory[0].category_id;

    await queryRunner.query(`
      INSERT INTO country_recommended_categories (country_id, category_id, order_by)
      SELECT c.id, '${allCategoryId}', 0
      FROM countries c
      WHERE c.deleted_at IS NULL
      ON CONFLICT (country_id, category_id) DO NOTHING
    `);
  }

  public async down(queryRunner: QueryRunner): Promise<void> {
    await queryRunner.query(`
      DELETE FROM country_recommended_categories
      WHERE category_id IN (
        SELECT category_id
        FROM category_translations
        WHERE slug = 'all'
          AND language_code = 'en'
          AND deleted_at IS NULL
      )
    `);
  }
}
