import { QueryInterface, DataTypes } from 'sequelize';

export async function up(queryInterface: QueryInterface): Promise<void> {
  // Add pause fields to approval_levels table
  // Note: The 'PAUSED' enum value is added in a separate migration (20250126-add-paused-to-enum.ts)
  await queryInterface.addColumn('approval_levels', 'is_paused', {
    type: DataTypes.BOOLEAN,
    allowNull: false,
    defaultValue: false
  });

  await queryInterface.addColumn('approval_levels', 'paused_at', {
    type: DataTypes.DATE,
    allowNull: true
  });

  await queryInterface.addColumn('approval_levels', 'paused_by', {
    type: DataTypes.UUID,
    allowNull: true,
    references: {
      model: 'users',
      key: 'user_id'
    }
  });

  await queryInterface.addColumn('approval_levels', 'pause_reason', {
    type: DataTypes.TEXT,
    allowNull: true
  });

  await queryInterface.addColumn('approval_levels', 'pause_resume_date', {
    type: DataTypes.DATE,
    allowNull: true
  });

  await queryInterface.addColumn('approval_levels', 'pause_tat_start_time', {
    type: DataTypes.DATE,
    allowNull: true,
    comment: 'Original TAT start time before pause'
  });

  await queryInterface.addColumn('approval_levels', 'pause_elapsed_hours', {
    type: DataTypes.DECIMAL(10, 2),
    allowNull: true,
    comment: 'Elapsed hours at pause time'
  });

  // Create index on is_paused for faster queries
  await queryInterface.sequelize.query(
    'CREATE INDEX IF NOT EXISTS "approval_levels_is_paused" ON "approval_levels" ("is_paused");'
  );

  // Create index on pause_resume_date for auto-resume job
  await queryInterface.sequelize.query(
    'CREATE INDEX IF NOT EXISTS "approval_levels_pause_resume_date" ON "approval_levels" ("pause_resume_date") WHERE "is_paused" = true;'
  );
}

export async function down(queryInterface: QueryInterface): Promise<void> {
  await queryInterface.removeColumn('approval_levels', 'pause_elapsed_hours');
  await queryInterface.removeColumn('approval_levels', 'pause_tat_start_time');
  await queryInterface.removeColumn('approval_levels', 'pause_resume_date');
  await queryInterface.removeColumn('approval_levels', 'pause_reason');
  await queryInterface.removeColumn('approval_levels', 'paused_by');
  await queryInterface.removeColumn('approval_levels', 'paused_at');
  await queryInterface.removeColumn('approval_levels', 'is_paused');
  
  // Note: PostgreSQL doesn't support removing enum values directly
  // To fully rollback, you would need to recreate the enum type
  // This is a limitation of PostgreSQL enums
  // For now, we'll leave 'PAUSED' in the enum even after rollback
}

