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

/**
 * PHASE 1: Log Model
 * Stores server and browser logs for debugging and monitoring
 * Includes automatic timestamp and user tracking
 */
const Log = sequelize.define('Log', {
  id: {
    type: DataTypes.UUID,
    defaultValue: DataTypes.UUIDV4,
    primaryKey: true
  },
  userId: {
    type: DataTypes.UUID,
    allowNull: true,
    index: true,
    references: {
      model: 'Users',
      key: 'id'
    }
  },
  level: {
    type: DataTypes.ENUM('log', 'warn', 'error', 'info', 'debug'),
    defaultValue: 'log',
    index: true
  },
  source: {
    type: DataTypes.ENUM('server', 'browser'),
    defaultValue: 'server',
    index: true
  },
  message: {
    type: DataTypes.TEXT,
    allowNull: false
  },
  context: {
    type: DataTypes.JSON,
    allowNull: true,
    comment: 'Additional context like stack trace, request details, etc.'
  },
  userAgent: {
    type: DataTypes.STRING,
    allowNull: true,
    comment: 'Browser user agent for browser logs'
  },
  url: {
    type: DataTypes.STRING,
    allowNull: true,
    comment: 'Page URL for browser logs'
  },
  timestamp: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW,
    index: true
  }
}, {
  tableName: 'logs',
  timestamps: true,
  indexes: [
    { fields: ['userId', 'timestamp'] },
    { fields: ['level', 'timestamp'] },
    { fields: ['source', 'timestamp'] }
  ]
});

export default Log;
