package com.red.circle.other.infra.database.mongo.service.activity.impl;

import com.google.common.collect.Lists;
import com.mongodb.client.model.Filters;
import com.red.circle.component.mongodb.config.MongoPrimaryService;
import com.red.circle.other.infra.database.mongo.entity.activity.ConsumeActivityCount;
import com.red.circle.other.infra.database.mongo.service.activity.ConsumeActivityCountService;
import com.red.circle.tool.core.date.TimestampUtils;
import com.red.circle.tool.core.text.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

/**
 * 消耗活动.
 *
 * @author pengshigang on 2023/5/25
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ConsumeActivityCountServiceImpl implements ConsumeActivityCountService {

  private final MongoTemplate mongoTemplate;
  private final MongoPrimaryService mongoPrimaryService;

  @Override
  public void incrTarget(Long userId, String regionId, Long target) {

    if (target <= 0 || StringUtils.isBlank(regionId)) {
      return;
    }

    String id = userId + "_" + regionId;

    if (existsPrimaryUnpaid(id)) {

      mongoTemplate.updateFirst(Query.query(Criteria.where("id").is(id)),
          new Update().inc("target", target), ConsumeActivityCount.class);
      return;
    }

    mongoTemplate.save(new ConsumeActivityCount()
        .setId(id)
        .setRegionId(regionId)
        .setUserId(userId)
        .setTarget(target)
        .setReceivedIds(Lists.newArrayList())
        .setCreateTime(TimestampUtils.now())
        .setExpiredTime(TimestampUtils.nowPlusDays(150))
    );

  }

  @Override
  public ConsumeActivityCount getById(String id) {

    return mongoTemplate
        .findOne(Query.query(Criteria.where("id").is(id)), ConsumeActivityCount.class);
  }

  @Override
  public void received(String id, String rewardId) {

    if (Boolean.FALSE.equals(existsPrimaryUnpaid(id))) {
      return;
    }

    mongoTemplate.updateFirst(Query.query(Criteria.where("id").is(id)),
        new Update().push("receivedIds", rewardId), ConsumeActivityCount.class);
  }

  private boolean existsPrimaryUnpaid(String id) {

    return mongoPrimaryService.exists("consume_activity_count",
        Filters.eq("_id", id)
    );
  }

}
