package com.xindazhou.business.controller.app.version;

import com.xindazhou.framework.common.pojo.CommonResult;
import com.xindazhou.business.controller.app.version.vo.AppVersionRespVO;
import com.xindazhou.business.convert.version.VersionConvert;
import com.xindazhou.business.dal.dataobject.version.VersionDO;
import com.xindazhou.business.service.version.VersionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import static com.xindazhou.framework.common.pojo.CommonResult.success;

/**
 * App 版本检查 Controller
 *
 * @author xindazhou
 */
@Tag(name = "App - 版本检查")
@RestController
@RequestMapping("/app-api/version")
@Validated
public class AppVersionController {

    @Resource
    private VersionService versionService;

    @GetMapping("/latest")
    @Operation(summary = "获取最新版本（用于APP检查更新）")
    @Parameter(name = "platform", description = "平台类型：1-安卓，2-鸿蒙，3-iOS", required = true, example = "1")
    @Parameter(name = "currentVersionCode", description = "当前版本号（可选，用于判断是否有更新）", example = "100")
    public CommonResult<AppVersionRespVO> getLatestVersion(
            @RequestParam("platform") Integer platform,
            @RequestParam(value = "currentVersionCode", required = false) Integer currentVersionCode) {
        
        // 获取最新版本（如果没有版本，返回 null）
        VersionDO latestVersion = versionService.getLatestVersion(platform);
        
        // 如果没有版本，返回空结果（前端会处理）
        if (latestVersion == null) {
            AppVersionRespVO respVO = new AppVersionRespVO();
            respVO.setHasUpdate(false);
            respVO.setForceUpdate(false);
            return success(respVO);
        }
        
        // 转换为响应对象
        AppVersionRespVO respVO = VersionConvert.INSTANCE.convertApp(latestVersion);
        
        // 判断是否有更新（如果提供了当前版本号）
        if (currentVersionCode != null) {
            respVO.setHasUpdate(latestVersion.getVersionCode() > currentVersionCode);
        } else {
            respVO.setHasUpdate(true); // 如果没有提供当前版本号，默认认为有新版本
        }
        
        return success(respVO);
    }

}

