'use strict';

/**
 * Migration: Fix project_audio_tracks.environment NULL constraint
 *
 * Unlike tour_pages and transitions, project_audio_tracks.environment allows NULL.
 * This migration fixes it to match other models - NOT NULL with default 'dev'.
 */
module.exports = {
  async up(queryInterface, Sequelize) {
    // Check if column exists
    const [columns] = await queryInterface.sequelize.query(
      `SELECT column_name FROM information_schema.columns
       WHERE table_name = 'project_audio_tracks' AND column_name = 'environment'`,
      { type: Sequelize.QueryTypes.SELECT },
    );

    if (!columns) {
      console.log(
        'Column project_audio_tracks.environment does not exist, skipping',
      );
      return;
    }

    // Set NULL values to 'dev'
    await queryInterface.sequelize.query(
      `UPDATE project_audio_tracks SET environment = 'dev' WHERE environment IS NULL`,
    );

    // Alter column to NOT NULL with default
    await queryInterface.changeColumn('project_audio_tracks', 'environment', {
      type: Sequelize.ENUM('dev', 'stage', 'production'),
      allowNull: false,
      defaultValue: 'dev',
    });

    console.log(
      'Successfully fixed project_audio_tracks.environment to NOT NULL with default dev',
    );
  },

  async down(queryInterface, Sequelize) {
    // Revert to allow NULL
    await queryInterface.changeColumn('project_audio_tracks', 'environment', {
      type: Sequelize.ENUM('dev', 'stage', 'production'),
      allowNull: true,
      defaultValue: 'dev',
    });

    console.log('Reverted project_audio_tracks.environment to allow NULL');
  },
};
