// models/user.js
'use strict';
const { Model } = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class User extends Model {
    static associate(models) {
      User.belongsTo(models.Store, { foreignKey: 'storeId', as: 'store' });
      User.hasMany(models.Session, { foreignKey: 'userId', as: 'sessions' });
      User.hasMany(models.Transaction, { foreignKey: 'cashierId', as: 'transactions' });

      

      
      
      User.hasMany(models.AuditLog, { foreignKey: 'userId', as: 'auditLogs' });
      User.hasMany(models.StockMovement, { foreignKey: 'performedBy', as: 'stockMovements' });
      User.hasMany(models.CashDrawerActivity, { foreignKey: 'performedBy', as: 'cashActivities' });
      User.hasMany(models.Payment, { foreignKey: 'processedBy', as: 'payments' });
      User.hasMany(models.Register, { foreignKey: 'openedBy', as: 'openedRegisters' });
      

       User.hasMany(models.RegisterAssignment, {
    foreignKey: 'userId',
    as: 'registerAssignments'
  });

  // For tracking who assigned users to registers
  User.hasMany(models.RegisterAssignment, {
    foreignKey: 'assignedBy',
    as: 'assignmentsMade'
  });

  User.hasMany(models.Order, {
  foreignKey: 'userId',
  as: 'orders'
});

  // Convenience association to get currently assigned registers directly
  User.belongsToMany(models.Register, {
    through: models.RegisterAssignment,
    foreignKey: 'userId',
    otherKey: 'registerId',
    as: 'assignedRegisters',
    scope: { isActive: true }
  });
      
    }
  }
  User.init({
    firstName: DataTypes.STRING,
    lastName: DataTypes.STRING,
    username: { type: DataTypes.STRING, unique: true },
    email: { type: DataTypes.STRING, unique: true },
    password: DataTypes.STRING,
    phone: DataTypes.STRING,
    role: DataTypes.STRING,
    pin: DataTypes.STRING,
    pinHint: DataTypes.STRING,
    storeId: DataTypes.INTEGER,
    lastLogin: DataTypes.DATE,
    isActive: { type: DataTypes.BOOLEAN, defaultValue: true }
  }, {
    sequelize,
    modelName: 'User',
    tableName: 'users',
    timestamps: true
  });
  return User;
};
