package com.red.circle.other.app.inner.endpoint.activity;

import com.red.circle.framework.dto.ResultResponse;
import com.red.circle.other.infra.database.rds.entity.activity.LotteryUserCount;
import com.red.circle.other.infra.database.rds.service.activity.LotteryUserCountService;
import com.red.circle.other.inner.endpoint.activity.api.LotteryUserCountClientApi;
import java.time.LocalDate;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户抽奖次数统计ClientEndpoint.
 *
 * @author system
 * @since 2025-10-18
 */
@Validated
@RestController
@RequestMapping(value = LotteryUserCountClientApi.API_PREFIX, produces = MediaType.APPLICATION_JSON_VALUE)
@RequiredArgsConstructor
public class LotteryUserCountClientEndpoint implements LotteryUserCountClientApi {

  private final LotteryUserCountService lotteryUserCountService;

  @Override
  public ResultResponse<Integer> getTodayCount(Long userId, Long activityId) {
    LotteryUserCount userCount = lotteryUserCountService.query()
        .eq(LotteryUserCount::getUserId, userId)
        .eq(LotteryUserCount::getActivityId, activityId)
        .eq(LotteryUserCount::getDrawDate, LocalDate.now())
        .getOne();
    
    int count = userCount != null ? userCount.getDrawCount() : 0;
    
    return ResultResponse.success(count);
  }

  @Override
  public ResultResponse<Void> incrDrawCount(Long userId, Long activityId) {
    LotteryUserCount userCount = lotteryUserCountService.query()
        .eq(LotteryUserCount::getUserId, userId)
        .eq(LotteryUserCount::getActivityId, activityId)
        .eq(LotteryUserCount::getDrawDate, LocalDate.now())
        .getOne();
    
    if (userCount == null) {
      userCount = new LotteryUserCount();
      userCount.setUserId(userId);
      userCount.setActivityId(activityId);
      userCount.setDrawDate(LocalDate.now());
      userCount.setDrawCount(1);
      lotteryUserCountService.save(userCount);
    } else {
      lotteryUserCountService.update()
          .eq(LotteryUserCount::getId, userCount.getId())
          .setSql("draw_count = draw_count + 1")
          .execute();
    }
    
    return ResultResponse.success();
  }

}
