'use strict';

module.exports = {
  async up(queryInterface, Sequelize) {
    await queryInterface.createTable('permission_audit', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      user_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        references: {
          model: 'user',
          key: 'id'
        },
        onUpdate: 'CASCADE',
        onDelete: 'CASCADE',
        comment: 'User who performed the action'
      },
      permission_code: {
        type: Sequelize.STRING(100),
        allowNull: false,
        comment: 'Permission code that was checked'
      },
      action: {
        type: Sequelize.ENUM('GRANTED', 'REVOKED', 'DENIED'),
        allowNull: false,
        comment: 'Action performed: GRANTED (access allowed), REVOKED (permission removed), DENIED (access denied)'
      },
      resource_type: {
        type: Sequelize.STRING(100),
        allowNull: true,
        comment: 'Type of resource accessed (e.g., purchase_order, material)'
      },
      resource_id: {
        type: Sequelize.INTEGER,
        allowNull: true,
        comment: 'ID of the resource accessed'
      },
      ip_address: {
        type: Sequelize.STRING(45),
        allowNull: true,
        comment: 'IP address of the user'
      },
      user_agent: {
        type: Sequelize.STRING(500),
        allowNull: true,
        comment: 'User agent string'
      },
      created_at: {
        allowNull: false,
        type: Sequelize.DATE,
        defaultValue: Sequelize.literal('CURRENT_TIMESTAMP')
      }
    });

    // Add indexes
    await queryInterface.addIndex('permission_audit', ['user_id'], {
      name: 'idx_permission_audit_user'
    });
    await queryInterface.addIndex('permission_audit', ['permission_code'], {
      name: 'idx_permission_audit_permission'
    });
    await queryInterface.addIndex('permission_audit', ['created_at'], {
      name: 'idx_permission_audit_created_at'
    });
    await queryInterface.addIndex('permission_audit', ['resource_type', 'resource_id'], {
      name: 'idx_permission_audit_resource'
    });
  },

  async down(queryInterface, Sequelize) {
    await queryInterface.dropTable('permission_audit');
  }
};

