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

const Member = sequelize.define('Member', {
  id: {
    type: DataTypes.INTEGER.UNSIGNED,
    primaryKey: true,
    autoIncrement: true,
    comment: '회원 고유 식별자'
  },
  clubId: {
    type: DataTypes.INTEGER.UNSIGNED,
    allowNull: false,
    references: {
      model: 'Clubs',
      key: 'id'
    },
    comment: '소속 클럽 ID'
  },
  userId: {
    type: DataTypes.INTEGER.UNSIGNED,
    allowNull: true,
    references: {
      model: 'Users',
      key: 'id'
    },
    comment: '유저 ID'
  },
  name: {
    type: DataTypes.STRING,
    allowNull: false,
    comment: '회원 이름'
  },
  gender: {
    type: DataTypes.ENUM('male', 'female'),
    allowNull: false,
    comment: '성별'
  },
  memberType: {
    type: DataTypes.ENUM('regular', 'associate', 'guest', 'manager', 'owner'),
    allowNull: false,
    defaultValue: 'regular',
    comment: '회원 유형'
  },
  handicap: {
    type: DataTypes.INTEGER,
    allowNull: false,
    defaultValue: 0,
    comment: '핸디캡'
  },
  phone: {
    type: DataTypes.STRING,
    allowNull: true,
    comment: '전화번호 (암호화됨)',
    get() {
      const rawValue = this.getDataValue('phone');
      return rawValue ? decrypt(rawValue) : null;
    },
    set(value) {
      this.setDataValue('phone', value ? encrypt(value) : null);
    }
  },
  email: {
    type: DataTypes.STRING,
    allowNull: true,
    comment: '이메일 (암호화됨)',
    get() {
      const rawValue = this.getDataValue('email');
      return rawValue ? decrypt(rawValue) : null;
    },
    set(value) {
      this.setDataValue('email', value ? encrypt(value) : null);
    }
  },
  joinDate: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
    comment: '가입일'
  },
  status: {
    type: DataTypes.ENUM('active', 'inactive', 'suspended', 'deleted'),
    allowNull: false,
    defaultValue: 'active',
    comment: '회원 상태'
  }
}, {
  tableName: 'Members',
  comment: '클럽 회원 정보를 저장하는 테이블',
  timestamps: true
});
Member.associate = (models) => {
  // User와의 관계 설정
  Member.belongsTo(User, {foreignKey: 'userId'});

  // Club과의 관계 설정
  Member.belongsTo(Club, {foreignKey: 'clubId'});

  // EventParticipant와의 관계 설정
  Member.hasMany(models.EventParticipant, { foreignKey: 'memberId' });
};
module.exports = Member;
