package com.yupi.project.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.project.annotation.AuthCheck;
import com.yupi.project.common.BaseResponse;
import com.yupi.project.common.DeleteRequest;
import com.yupi.project.common.ErrorCode;
import com.yupi.project.common.ResultUtils;
import com.yupi.project.constant.UserConstant;
import com.yupi.project.exception.BusinessException;
import com.yupi.project.exception.ThrowUtils;
import com.yupi.project.model.dto.activationcode.ActivationCodeQueryRequest;
import com.yupi.project.model.dto.activationcode.GenerateCodesRequest;
import com.yupi.project.model.dto.activationcode.RedeemCodeRequest;
import com.yupi.project.model.dto.common.IdRequest;
import com.yupi.project.model.entity.ActivationCode;
import com.yupi.project.model.entity.User;
import com.yupi.project.model.vo.ActivationCodeVO;
import com.yupi.project.service.ActivationCodeService;
import com.yupi.project.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/activation-code")
@Slf4j
public class ActivationCodeController {

    @Resource
    private ActivationCodeService activationCodeService;

    @Resource
    private UserService userService;

    // region 用户操作

    /**
     * 用户兑换激活码
     *
     * @param redeemCodeRequest 激活码请求
     * @param request           HTTP请求
     * @return 是否成功
     */
    @PostMapping("/redeem")
    public BaseResponse<Boolean> redeemActivationCode(@RequestBody RedeemCodeRequest redeemCodeRequest, HttpServletRequest request) {
        if (redeemCodeRequest == null || redeemCodeRequest.getCode() == null || redeemCodeRequest.getCode().trim().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "激活码不能为空");
        }
        User loginUser = userService.getCurrentUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR, "用户未登录或登录已失效");
        }
        boolean result = activationCodeService.redeemCode(loginUser.getId(), redeemCodeRequest.getCode());
        return ResultUtils.success(result);
    }

    // endregion

    // region 管理员操作

    /**
     * 管理员批量生成激活码
     *
     * @param generateCodesRequest 生成请求
     * @return 生成的激活码列表 (只返回code，避免信息过多，或根据需要返回VO)
     */
    @PostMapping("/admin/generate")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<List<ActivationCodeVO>> generateActivationCodes(@RequestBody GenerateCodesRequest generateCodesRequest) {
        if (generateCodesRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (generateCodesRequest.getCount() == null || generateCodesRequest.getCount() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "生成数量必须大于0");
        }
        if (generateCodesRequest.getValue() == null || generateCodesRequest.getValue().signum() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "面值必须大于0");
        }

        try {
            List<ActivationCode> codes = activationCodeService.generateCodes(
                    generateCodesRequest.getCount(),
                    generateCodesRequest.getValue(),
                    generateCodesRequest.getExpireTime(),
                    generateCodesRequest.getBatchId()
            );
            List<ActivationCodeVO> voList = codes.stream()
                    .map(code -> {
                        ActivationCodeVO vo = new ActivationCodeVO();
                        BeanUtils.copyProperties(code, vo);
                        return vo;
                    })
                    .collect(Collectors.toList());
            return ResultUtils.success(voList);
        } catch (Exception e) {
            log.error("Error generating activation codes", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, e.getMessage());
        }
    }

    /**
     * 管理员分页查询激活码
     *
     * @param activationCodeQueryRequest 查询条件
     * @return 分页的激活码视图对象
     */
    @PostMapping("/admin/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<ActivationCodeVO>> listActivationCodesByPage(@RequestBody ActivationCodeQueryRequest activationCodeQueryRequest) {
        if (activationCodeQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long current = activationCodeQueryRequest.getCurrent();
        long size = activationCodeQueryRequest.getPageSize();
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        
        Page<ActivationCode> activationCodePage = activationCodeService.page(new Page<>(current, size),
                activationCodeService.getQueryWrapper(activationCodeQueryRequest));
        
        Page<ActivationCodeVO> activationCodeVOPage = new Page<>(activationCodePage.getCurrent(), activationCodePage.getSize(), activationCodePage.getTotal());
        List<ActivationCodeVO> activationCodeVOList = activationCodePage.getRecords().stream().map(activationCode -> {
            ActivationCodeVO activationCodeVO = new ActivationCodeVO();
            BeanUtils.copyProperties(activationCode, activationCodeVO);
            if (activationCode.getIsUsed() == 1 && activationCode.getUserId() != null) {
                User user = userService.getById(activationCode.getUserId());
                if (user != null) {
                    activationCodeVO.setUserName(user.getUsername());
                }
            }
            return activationCodeVO;
        }).collect(Collectors.toList());
        activationCodeVOPage.setRecords(activationCodeVOList);

        return ResultUtils.success(activationCodeVOPage);
    }

    /**
     * 管理员删除激活码
     *
     * @param idRequest 包含激活码ID的请求体
     * @param request HTTP请求 (用于权限校验等)
     * @return 是否成功
     */
    @PostMapping("/admin/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteActivationCode(@RequestBody IdRequest idRequest, HttpServletRequest request) {
        if (idRequest == null || idRequest.getId() == null || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "激活码ID不能为空");
        }
        boolean result = activationCodeService.deleteCode(idRequest.getId());
        return ResultUtils.success(result);
    }
    
    // endregion
} 