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.LotteryActivity;
import com.red.circle.other.infra.database.rds.service.activity.LotteryActivityService;
import com.red.circle.other.inner.endpoint.activity.api.LotteryActivityClientApi;
import com.red.circle.other.inner.model.dto.activity.LotteryActivityDTO;
import java.util.List;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
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 = LotteryActivityClientApi.API_PREFIX, produces = MediaType.APPLICATION_JSON_VALUE)
@RequiredArgsConstructor
public class LotteryActivityClientEndpoint implements LotteryActivityClientApi {

  private final LotteryActivityService lotteryActivityService;

  @Override
  public ResultResponse<LotteryActivityDTO> getByActivityCode(String activityCode) {
    LotteryActivity activity = lotteryActivityService.query()
        .eq(LotteryActivity::getActivityCode, activityCode)
        .getOne();
    
    if (activity == null) {
      return ResultResponse.success(null);
    }
    
    return ResultResponse.success(convertToDTO(activity));
  }

  @Override
  public ResultResponse<LotteryActivityDTO> getById(Long id) {
    LotteryActivity activity = lotteryActivityService.getById(id);
    
    if (activity == null) {
      return ResultResponse.success(null);
    }
    
    return ResultResponse.success(convertToDTO(activity));
  }

  @Override
  public ResultResponse<List<LotteryActivityDTO>> listActivities() {
    List<LotteryActivity> activities = lotteryActivityService.query()
        .eq(LotteryActivity::getStatus, 1)
        .orderByDesc(LotteryActivity::getCreateTime)
        .list();
    
    List<LotteryActivityDTO> dtoList = activities.stream()
        .map(this::convertToDTO)
        .collect(Collectors.toList());
    
    return ResultResponse.success(dtoList);
  }

  private LotteryActivityDTO convertToDTO(LotteryActivity activity) {
    LotteryActivityDTO dto = new LotteryActivityDTO();
    BeanUtils.copyProperties(activity, dto);
    return dto;
  }

}
