const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');
const bcrypt = require('bcrypt');
const { encrypt, decrypt } = require('../utils/encryption');

const User = sequelize.define('User', {
  id: {
    type: DataTypes.INTEGER.UNSIGNED,
    primaryKey: true,
    autoIncrement: true,
    comment: '유저 고유 식별자'
  },
  username: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true,
    comment: '로그인 계정명'
  },
  password: {
    type: DataTypes.STRING,
    allowNull: false,
    comment: '비밀번호(해시)'
  },
  name: {
    type: DataTypes.STRING,
    allowNull: false,
    comment: '이름'
  },
  email: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true,
    comment: '이메일 (암호화됨)',
    get() {
      const rawValue = this.getDataValue('email');
      return rawValue ? decrypt(rawValue) : null;
    },
    set(value) {
      this.setDataValue('email', value ? encrypt(value) : null);
    }
  },
  role: {
    type: DataTypes.ENUM('admin', 'clubadmin', 'user'),
    allowNull: false,
    defaultValue: 'user',
    comment: '권한 역할'
  },
  status: {
    type: DataTypes.ENUM('active', 'inactive', 'suspended'),
    allowNull: false,
    defaultValue: 'active',
    comment: '계정 상태'
  },
  lastLoginAt: {
    type: DataTypes.DATE,
    allowNull: true,
    comment: '마지막 로그인 일시'
  },
  createdAt: {
    type: DataTypes.DATE,
    allowNull: false,
    comment: '생성일'
  },
  updatedAt: {
    type: DataTypes.DATE,
    allowNull: false,
    comment: '수정일'
  }
}, {
  tableName: 'Users',
  comment: '서비스 회원(유저) 정보를 저장하는 테이블',
  timestamps: true,
  hooks: {
    beforeCreate: async (user) => {
      if (user.password) {
        const salt = await bcrypt.genSalt(10);
        user.password = await bcrypt.hash(user.password, salt);
      }
    },
    beforeUpdate: async (user) => {
      if (user.changed('password')) {
        const salt = await bcrypt.genSalt(10);
        user.password = await bcrypt.hash(user.password, salt);
      }
    }
  }
});

// 비밀번호 검증 메소드
User.prototype.validatePassword = async function(password) {
  return await bcrypt.compare(password, this.password);
};

User.associate = (models) => {
  User.hasMany(models.Notification, { foreignKey: 'userId' });
};

module.exports = User;
