-- Migration: Create api_log table for comprehensive request/response and execution logging

CREATE TABLE IF NOT EXISTS api_log (
  id INT AUTO_INCREMENT PRIMARY KEY,
  user_id INT NULL,
  method VARCHAR(10) NOT NULL COMMENT 'HTTP method (GET, POST, PUT, DELETE, etc.)',
  path VARCHAR(500) NOT NULL COMMENT 'Request path',
  status_code INT NULL COMMENT 'HTTP status code',
  request_body TEXT NULL COMMENT 'Request body (truncated if too long)',
  response_body TEXT NULL COMMENT 'Response body (truncated if too long)',
  execution_time INT NULL COMMENT 'Execution time in milliseconds',
  error_message TEXT NULL COMMENT 'Error message if request failed',
  ip_address VARCHAR(45) NULL COMMENT 'Client IP address',
  user_agent VARCHAR(500) NULL COMMENT 'User agent string',
  log_type ENUM('api_request', 'scheduler', 'cron_job', 'manual') NOT NULL DEFAULT 'api_request' COMMENT 'Type of log entry',
  scheduler_job_type VARCHAR(50) NULL COMMENT 'Type of scheduler job (rating_updates, match_results, etc.)',
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  FOREIGN KEY (user_id) REFERENCES user(id) ON DELETE SET NULL ON UPDATE CASCADE,
  INDEX idx_api_log_user_id (user_id, created_at),
  INDEX idx_api_log_path (path, created_at),
  INDEX idx_api_log_log_type (log_type, created_at),
  INDEX idx_api_log_created_at (created_at),
  INDEX idx_api_log_status_code (status_code)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

