const { DataTypes } = require('sequelize');
const { generateApiKey, generateApiSecret } = require('../utils/helpers');

// Session Model
module.exports = (sequelize) => {
  const Session = sequelize.define('Session', {
    id: {
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
      primaryKey: true,
    },
    userId: {
      type: DataTypes.BIGINT.UNSIGNED,
      allowNull: false,
      field: 'user_id',
      references: {
        model: 'users',
        key: 'id',
      },
    },
    token: {
      type: DataTypes.STRING(500),
      allowNull: false,
    },
    refreshToken: {
      type: DataTypes.STRING(500),
      field: 'refresh_token',
    },
    device: {
      type: DataTypes.STRING(255),
    },
    browser: {
      type: DataTypes.STRING(100),
    },
    os: {
      type: DataTypes.STRING(100),
    },
    ip: {
      type: DataTypes.STRING(45),
    },
    location: {
      type: DataTypes.STRING(255),
    },
    isActive: {
      type: DataTypes.BOOLEAN,
      defaultValue: true,
      field: 'is_active',
    },
    lastActiveAt: {
      type: DataTypes.DATE,
      defaultValue: DataTypes.NOW,
      field: 'last_active_at',
    },
    expiresAt: {
      type: DataTypes.DATE,
      field: 'expires_at',
    },
    revokedAt: {
      type: DataTypes.DATE,
      field: 'revoked_at',
    },
    metadata: {
      type: DataTypes.JSON,
      defaultValue: {},
    },
  }, {
    tableName: 'sessions',
    timestamps: true,
    underscored: true,
    indexes: [
      { fields: ['user_id'] },
      { fields: ['token'] },
      { fields: ['is_active'] },
    ],
  });

  // Instance Methods
  Session.prototype.revoke = async function () {
    this.isActive = false;
    this.revokedAt = new Date();
    return this.save();
  };

  Session.prototype.updateActivity = async function () {
    this.lastActiveAt = new Date();
    return this.save();
  };

  return Session;
};

// API Key Model

