const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');

/**
 * User Model
 * Represents users of the mini program
 */
const User = sequelize.define('User', {
  id: {
    type: DataTypes.UUID,
    defaultValue: DataTypes.UUIDV4,
    primaryKey: true,
  },
  uid: {
    type: DataTypes.STRING(6),
    allowNull: true,
    unique: true,
    comment: '6位数字用户ID，用于展示',
  },
  wechatOpenId: {
    type: DataTypes.STRING(100),
    allowNull: false,
    unique: true,
    field: 'wechat_open_id',
  },
  wechatUnionId: {
    type: DataTypes.STRING(100),
    allowNull: true,
    field: 'wechat_union_id',
  },
  nickname: {
    type: DataTypes.STRING(100),
    allowNull: true,
  },
  avatar: {
    type: DataTypes.STRING(500),
    allowNull: true,
  },
  realName: {
    type: DataTypes.STRING(100),
    allowNull: true,
    field: 'real_name',
  },
  phone: {
    type: DataTypes.STRING(20),
    allowNull: true,
  },
  whatsapp: {
    type: DataTypes.STRING(20),
    allowNull: true,
  },
  wechatId: {
    type: DataTypes.STRING(100),
    allowNull: true,
    field: 'wechat_id',
  },
  language: {
    type: DataTypes.ENUM('zh', 'en', 'pt'),
    defaultValue: 'zh',
    allowNull: false,
  },
  balance: {
    type: DataTypes.DECIMAL(10, 2),
    defaultValue: 0.00,
    allowNull: false,
  },
  invitationCode: {
    type: DataTypes.STRING(20),
    allowNull: true,
    unique: true,
    field: 'invitation_code',
  },
  invitedBy: {
    type: DataTypes.UUID,
    allowNull: true,
    field: 'invited_by',
    references: {
      model: 'user',
      key: 'id',
    },
  },
  status: {
    type: DataTypes.ENUM('active', 'suspended'),
    defaultValue: 'active',
    allowNull: false,
  },
}, {
  tableName: 'user',
  timestamps: true,
  underscored: true,
  indexes: [
    { fields: ['uid'], unique: true },
    { fields: ['wechat_open_id'] },
    { fields: ['invitation_code'] },
    { fields: ['status'] },
  ],
  hooks: {
    beforeCreate: async (user) => {
      // 生成唯一的6位数字UID
      if (!user.uid) {
        user.uid = await generateUniqueUid();
      }
    },
  },
});

/**
 * 生成唯一的6位数字UID
 * 从100000开始，确保是6位数
 */
async function generateUniqueUid() {
  const maxAttempts = 100;
  
  for (let i = 0; i < maxAttempts; i++) {
    // 生成100000-999999之间的随机数
    const uid = String(Math.floor(100000 + Math.random() * 900000));
    
    // 检查是否已存在
    const existing = await User.findOne({ where: { uid } });
    if (!existing) {
      return uid;
    }
  }
  
  // 如果随机生成失败，使用递增方式
  const lastUser = await User.findOne({
    where: { uid: { [require('sequelize').Op.ne]: null } },
    order: [['uid', 'DESC']],
  });
  
  if (lastUser && lastUser.uid) {
    const nextUid = parseInt(lastUser.uid) + 1;
    if (nextUid <= 999999) {
      return String(nextUid);
    }
  }
  
  // 从100001开始
  return '100001';
}

module.exports = User;
