'use strict';
const { CrudService } = require('naf-framework-mongoose-free/lib/service');
const { BusinessError, ErrorCode } = require('naf-core').Error;
const _ = require('lodash');
const assert = require('assert');

// 团队表
class TeamService extends CrudService {
  constructor(ctx) {
    super(ctx, 'team');
    this.model = this.ctx.model.Team;
  }
  // 用户退出团队
  async leaves({ team_id, user_id } = {}) {
    const res = await this.model.findById(team_id);
    if (!res) throw new BusinessError(ErrorCode.DATA_NOT_EXIST);
    const members = res.members.filter(i => i.user_id !== user_id);
    res.members = members;
    await res.save();
  }
  // 用户所在团队列表
  async userteams({ user_id } = {}) {
    const res = await this.model.find({ members: { $elemMatch: { user_id: user_id } } });
    if (!res) throw new BusinessError(ErrorCode.DATA_NOT_EXIST);
    return res;
  }
}

module.exports = TeamService;