package com.red.circle.other.app.inner.service.team.impl;

import com.red.circle.component.redis.service.RedisService;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.other.infra.convertor.team.TeamInfraConvertor;
import com.red.circle.other.infra.database.cache.key.TeamNoticeKeys;
import com.red.circle.other.infra.database.mongo.entity.team.team.TeamNotice;
import com.red.circle.other.infra.database.mongo.entity.team.team.TeamProfile;
import com.red.circle.other.infra.database.mongo.service.team.team.TeamNoticeService;
import com.red.circle.other.infra.database.mongo.service.team.team.TeamProfileService;
import com.red.circle.other.app.inner.service.team.TeamNoticeClientService;
import com.red.circle.other.inner.model.cmd.team.TeamNoticeCmd;
import com.red.circle.other.inner.model.dto.agency.agency.TeamNoticeDTO;
import com.red.circle.tool.core.sequence.IdWorkerUtils;
import java.util.List;
import java.util.concurrent.TimeUnit;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 团队通知服务.
 *
 * @author lisizhe on 2023/5/26
 */
@Service
@RequiredArgsConstructor
public class TeamNoticeClientServiceImpl implements TeamNoticeClientService {

  private final RedisService redisService;
  private final TeamNoticeService teamNoticeService;
  private final TeamInfraConvertor teamInfraConvertor;
  private final TeamProfileService teamProfileService;

  @Override
  public List<TeamNoticeDTO> listByTeamId(Long teamId) {
    return teamInfraConvertor.toListTeamNoticeDTO(teamNoticeService.listByTeamId(teamId));
  }

  @Override
  public void sendNotice(TeamNoticeCmd cmd) {
    TeamProfile teamProfile = teamProfileService.getById(cmd.getTeamId());
    ResponseAssert.notNull(CommonErrorCode.NOT_FOUND_RECORD_INFO, teamProfile);

    TeamNotice teamNotice = teamInfraConvertor.toTeamNotice(cmd);
    teamNotice.setId(IdWorkerUtils.getId());
    teamNotice.setSysOrigin(teamProfile.getSysOrigin());
    teamNoticeService.add(teamNotice);

    redisService.setIfAbsent(TeamNoticeKeys.TEAM_NEW_NOTICE.getKey(teamProfile.getId()),
        1, 3, TimeUnit.DAYS);
  }

  @Override
  public void deleteById(Long id) {
    teamNoticeService.deleteById(id);
  }
}
