import { QueryInterface } from 'sequelize';

/**
 * Migration to ensure 'ORGANIZATIONAL' exists in the holiday_type enum
 * and set 'NATIONAL' as the default value for the holiday_type column.
 */
export async function up(queryInterface: QueryInterface): Promise<void> {
  // 1. Add 'ORGANIZATIONAL' to the enum_holidays_holiday_type enum type if it doesn't exist
  // PostgreSQL doesn't support IF NOT EXISTS for ALTER TYPE ADD VALUE,
  // so we check if it exists first using a PL/pgSQL block
  await queryInterface.sequelize.query(`
    DO $$
    BEGIN
      IF NOT EXISTS (
        SELECT 1 FROM pg_enum 
        WHERE enumlabel = 'ORGANIZATIONAL' 
        AND enumtypid = (SELECT oid FROM pg_type WHERE typname = 'enum_holidays_holiday_type')
      ) THEN
        ALTER TYPE enum_holidays_holiday_type ADD VALUE 'ORGANIZATIONAL';
      END IF;
    END$$;
  `);

  // 2. Set 'ORGANIZATIONAL' as the default value for the holiday_type column
  await queryInterface.sequelize.query(`
    ALTER TABLE "holidays" ALTER COLUMN "holiday_type" SET DEFAULT 'ORGANIZATIONAL';
  `);
}

export async function down(queryInterface: QueryInterface): Promise<void> {
  // PostgreSQL doesn't support removing enum values directly.
  // We can revert the default value back to 'ORGANIZATIONAL' if needed.
  await queryInterface.sequelize.query(`
    ALTER TABLE "holidays" ALTER COLUMN "holiday_type" SET DEFAULT 'NATIONAL';
  `);
  
  console.log('[Migration] Note: Cannot remove enum values in PostgreSQL. ORGANIZATIONAL will remain in enum_holidays_holiday_type.');
}
