"use strict";

module.exports = {
  async up(queryInterface, Sequelize) {
    // Add nullable weather_type_id column
    await queryInterface.sequelize.query(`
      ALTER TABLE IF EXISTS falukant_data.production
      ADD COLUMN IF NOT EXISTS weather_type_id integer;
    `);

    // Add foreign key constraint if not exists
    await queryInterface.sequelize.query(`
      DO $$
      BEGIN
        IF NOT EXISTS (
          SELECT 1
          FROM information_schema.table_constraints tc
          JOIN information_schema.key_column_usage kcu ON kcu.constraint_name = tc.constraint_name AND kcu.constraint_schema = tc.constraint_schema
          WHERE tc.constraint_type = 'FOREIGN KEY'
            AND tc.constraint_schema = 'falukant_data'
            AND tc.table_name = 'production'
            AND kcu.column_name = 'weather_type_id'
        ) THEN
          ALTER TABLE falukant_data.production
          ADD CONSTRAINT fk_production_weather_type
          FOREIGN KEY (weather_type_id) REFERENCES falukant_type.weather(id);
        END IF;
      END$$;
    `);

  // create index to speed lookups
    await queryInterface.sequelize.query(`
      DO $$
      BEGIN
        IF NOT EXISTS (
          SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
          WHERE c.relkind = 'i' AND c.relname = 'idx_production_weather_type_id' AND n.nspname = 'falukant_data'
        ) THEN
          CREATE INDEX idx_production_weather_type_id ON falukant_data.production (weather_type_id);
        END IF;
      END$$;
    `);
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.sequelize.query(`
      ALTER TABLE IF EXISTS falukant_data.production
      DROP CONSTRAINT IF EXISTS fk_production_weather_type;
    `);

    await queryInterface.sequelize.query(`
      DO $$
      BEGIN
        IF EXISTS (
          SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
          WHERE c.relkind = 'i' AND c.relname = 'idx_production_weather_type_id' AND n.nspname = 'falukant_data'
        ) THEN
          EXECUTE 'DROP INDEX falukant_data.idx_production_weather_type_id';
        END IF;
      END$$;
    `);

    await queryInterface.sequelize.query(`
      ALTER TABLE IF EXISTS falukant_data.production
      DROP COLUMN IF EXISTS weather_type_id;
    `);
  }
};
