import { DataTypes } from 'sequelize';

export default {
  up: async (queryInterface) => {
    const transaction = await queryInterface.sequelize.transaction();

    try {
      await queryInterface.createTable('config_audit_logs', {
        id: {
          type: DataTypes.UUID,
          defaultValue: DataTypes.UUIDV4,
          primaryKey: true
        },
        configId: {
          type: DataTypes.UUID,
          allowNull: false,
          field: 'config_id',
          references: {
            model: 'config_settings',
            key: 'id'
          },
          onDelete: 'CASCADE'
        },
        actorId: {
          type: DataTypes.UUID,
          allowNull: false,
          field: 'actor_id',
          references: {
            model: 'users', // Note: User table name usually lowercase in Postgres if created via Sequelize defaults, or "Users" if strictly quoted
            key: 'id'
          }
        },
        action: {
          type: DataTypes.ENUM('CREATE', 'UPDATE', 'DELETE'),
          allowNull: false
        },
        previousValue: {
          type: DataTypes.JSONB,
          allowNull: true,
          field: 'previous_value'
        },
        newValue: {
          type: DataTypes.JSONB,
          allowNull: true,
          field: 'new_value'
        },
        createdAt: {
          type: DataTypes.DATE,
          allowNull: false,
          defaultValue: DataTypes.NOW,
          field: 'created_at'
        }
      }, { transaction });

      // Add indexes for common query patterns
      await queryInterface.addIndex('config_audit_logs', ['config_id'], { transaction });
      await queryInterface.addIndex('config_audit_logs', ['actor_id'], { transaction });
      await queryInterface.addIndex('config_audit_logs', ['created_at'], { transaction });

      await transaction.commit();
    } catch (err) {
      await transaction.rollback();
      throw err;
    }
  },

  down: async (queryInterface) => {
    const transaction = await queryInterface.sequelize.transaction();
    try {
      await queryInterface.dropTable('config_audit_logs', { transaction });
      await queryInterface.sequelize.query('DROP TYPE IF EXISTS "enum_config_audit_logs_action";', { transaction });
      await transaction.commit();
    } catch (err) {
      await transaction.rollback();
      throw err;
    }
  }
};
