import { DataTypes } from 'sequelize';
import sequelize from '../database.js';
import User from './User.js';

const ApiLog = sequelize.define('ApiLog', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    allowNull: false,
  },
  userId: {
    type: DataTypes.INTEGER,
    allowNull: true,
    references: {
      model: User,
      key: 'id',
    },
    onDelete: 'SET NULL',
    onUpdate: 'CASCADE',
  },
  method: {
    type: DataTypes.STRING(10),
    allowNull: false,
    comment: 'HTTP method (GET, POST, PUT, DELETE, etc.)'
  },
  path: {
    type: DataTypes.STRING(500),
    allowNull: false,
    comment: 'Request path'
  },
  statusCode: {
    type: DataTypes.INTEGER,
    allowNull: true,
    comment: 'HTTP status code'
  },
  requestBody: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: 'Request body (truncated if too long)'
  },
  responseBody: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: 'Response body (truncated if too long)'
  },
  executionTime: {
    type: DataTypes.INTEGER,
    allowNull: true,
    comment: 'Execution time in milliseconds'
  },
  errorMessage: {
    type: DataTypes.TEXT,
    allowNull: true,
    comment: 'Error message if completes failed'
  },
  ipAddress: {
    type: DataTypes.STRING(45),
    allowNull: true,
    comment: 'Client IP address'
  },
  userAgent: {
    type: DataTypes.STRING(500),
    allowNull: true,
    comment: 'User agent string'
  },
  logType: {
    type: DataTypes.ENUM('api_request', 'scheduler', 'cron_job', 'manual'),
    allowNull: false,
    defaultValue: 'api_request',
    comment: 'Type of log entry'
  },
  schedulerJobType: {
    type: DataTypes.STRING(50),
    allowNull: true,
    comment: 'Type of scheduler job (rating_updates, match_results, etc.)'
  },
}, {
  underscored: true,
  tableName: 'api_log',
  timestamps: true,
  indexes: [
    {
      fields: ['user_id', 'created_at']
    },
    {
      fields: ['path', 'created_at']
    },
    {
      fields: ['log_type', 'created_at']
    },
    {
      fields: ['created_at']
    },
    {
      fields: ['status_code']
    }
  ]
});

export default ApiLog;

