"use strict";

const { DataTypes } = require("sequelize");

module.exports = (sequelize) => {
  const AuditLog = sequelize.define("AuditLog", {
    id: {
      type: DataTypes.BIGINT.UNSIGNED,
      autoIncrement: true,
      primaryKey: true,
      allowNull: false,
    },
    adminId: {
      type: DataTypes.BIGINT.UNSIGNED,
      allowNull: true,
      field: "admin_id",
    },
    action: {
      type: DataTypes.STRING(120),
      allowNull: false,
    },
    entityType: {
      type: DataTypes.STRING(80),
      allowNull: false,
      field: "entity_type",
    },
    entityId: {
      type: DataTypes.STRING(120),
      allowNull: true,
      field: "entity_id",
    },
    statusCode: {
      type: DataTypes.INTEGER,
      allowNull: true,
      field: "status_code",
    },
    ip: {
      type: DataTypes.STRING(60),
      allowNull: true,
    },
    userAgent: {
      type: DataTypes.STRING(255),
      allowNull: true,
      field: "user_agent",
    },
    requestBody: {
      type: DataTypes.JSON,
      allowNull: true,
      field: "request_body",
    },
    requestParams: {
      type: DataTypes.JSON,
      allowNull: true,
      field: "request_params",
    },
    requestQuery: {
      type: DataTypes.JSON,
      allowNull: true,
      field: "request_query",
    },
    durationMs: {
      type: DataTypes.INTEGER,
      allowNull: true,
      field: "duration_ms",
    },
    created_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
    },
    updated_at: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
    },
  }, {
    tableName: "audit_logs",
    underscored: true,
    timestamps: true,
    createdAt: "created_at",
    updatedAt: "updated_at",
  });

  AuditLog.associate = (models) => {
    if (models.Admin) {
      AuditLog.belongsTo(models.Admin, { as: "admin", foreignKey: "adminId" });
    }
  };

  return AuditLog;
};
