'use strict';

/**
 * Migration: Enforce environment NOT NULL on all environment-aware tables
 *
 * This migration ensures that:
 * 1. All NULL environment values are set to 'dev'
 * 2. environment column is NOT NULL with default 'dev'
 *
 * This prevents data leaks where pages without environment could appear in production.
 */
module.exports = {
  async up(queryInterface, _Sequelize) {
    // Fix any NULL environments in tour_pages
    await queryInterface.sequelize.query(
      `UPDATE tour_pages SET environment = 'dev' WHERE environment IS NULL`,
    );

    // Fix any NULL environments in transitions
    await queryInterface.sequelize.query(
      `UPDATE transitions SET environment = 'dev' WHERE environment IS NULL`,
    );

    // Add NOT NULL constraint with default to tour_pages.environment
    await queryInterface.sequelize.query(`
      ALTER TABLE tour_pages
        ALTER COLUMN environment SET NOT NULL,
        ALTER COLUMN environment SET DEFAULT 'dev'
    `);

    // Add NOT NULL constraint with default to transitions.environment
    await queryInterface.sequelize.query(`
      ALTER TABLE transitions
        ALTER COLUMN environment SET NOT NULL,
        ALTER COLUMN environment SET DEFAULT 'dev'
    `);

    console.log('Successfully enforced NOT NULL on environment columns');
  },

  async down(queryInterface, _Sequelize) {
    // Remove NOT NULL constraint from tour_pages.environment
    await queryInterface.sequelize.query(`
      ALTER TABLE tour_pages
        ALTER COLUMN environment DROP NOT NULL,
        ALTER COLUMN environment DROP DEFAULT
    `);

    // Remove NOT NULL constraint from transitions.environment
    await queryInterface.sequelize.query(`
      ALTER TABLE transitions
        ALTER COLUMN environment DROP NOT NULL,
        ALTER COLUMN environment DROP DEFAULT
    `);

    console.log('Removed NOT NULL constraint from environment columns');
  },
};
