// 管理员模型
const { adminDB } = require('../config/database');
const bcrypt = require('bcryptjs');

class Admin {
  constructor(data) {
    this.id = data.id;
    this.username = data.username;
    this.password = data.password;
    this.email = data.email;
    this.nickname = data.nickname;
    this.avatar = data.avatar;
    this.role = data.role;
    this.status = data.status;
    this.last_login = data.last_login;
    this.created_at = data.created_at;
    this.updated_at = data.updated_at;
  }

  // 根据用户名查找管理员
  static async findByUsername(username) {
    const adminData = await adminDB.findByUsername(username);
    return adminData ? new Admin(adminData) : null;
  }

  // 根据ID查找管理员
  static async findById(id) {
    const adminData = await adminDB.findById(id);
    return adminData ? new Admin(adminData) : null;
  }

  // 验证密码
  async verifyPassword(password) {
    return await bcrypt.compare(password, this.password);
  }

  // 更新最后登录时间
  async updateLastLogin() {
    await adminDB.updateLastLogin(this.id);
  }

  // 创建管理员
  static async create(adminData) {
    // 密码加密
    if (adminData.password) {
      adminData.password = await bcrypt.hash(adminData.password, 10);
    }
    
    const id = await adminDB.create(adminData);
    return await this.findById(id);
  }

  // 更新管理员信息
  async update(updateData) {
    // 如果有密码更新，需要加密
    if (updateData.password) {
      updateData.password = await bcrypt.hash(updateData.password, 10);
    }
    
    await adminDB.update(this.id, updateData);
    
    // 更新实例数据
    Object.assign(this, updateData);
  }

  // 删除管理员
  async delete() {
    await adminDB.delete(this.id);
  }

  // 转换为安全对象（不包含密码等敏感信息）
  toSafeObject() {
    return {
      id: this.id,
      username: this.username,
      email: this.email,
      nickname: this.nickname,
      avatar: this.avatar,
      role: this.role,
      status: this.status,
      last_login: this.last_login,
      created_at: this.created_at,
      updated_at: this.updated_at
    };
  }
}

module.exports = Admin;