package com.jeesharp.business.common.appversion.service;

import com.jeesharp.business.common.appversion.vo.AppVersionClientVO;
import com.jeesharp.business.common.appversion.vo.AppVersionListClientVO;
import com.jeesharp.business.common.appversion.vo.CheckUpdateClientVO;
import com.jeesharp.business.modules.setting.application.ClientAppVersionApplicationService;
import com.jeesharp.business.modules.setting.enums.ClientAppVersionTypeEnum;
import com.jeesharp.business.modules.setting.enums.ClientAppVersionUpdateStrategyEnum;
import com.jeesharp.business.modules.setting.vo.ClientAppVersionReleaseView;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 客户端版本查询：从库表 {@code cfg_client_app_version} 读取发布清单，按端筛选、分页与比较版本号。
 *
 * @author jeesharp
 * @since 2026-05-12
 */
@Service
@RequiredArgsConstructor
public class AppVersionMobileService {

    private final ClientAppVersionApplicationService clientAppVersionApplicationService;

    /**
     * 分页查询某端的版本更新记录（按 versionCode 降序）。
     */
    public AppVersionListClientVO list(int page, int pageSize, String platformRaw) {
        String platform = normalizePlatform(platformRaw);
        List<AppVersionClientVO> all = clientAppVersionApplicationService.listPublishedForPlatform(platform).stream()
                .map(AppVersionMobileService::toClientVo)
                .sorted(Comparator.comparing(AppVersionClientVO::getVersionCode, Comparator.nullsLast(Integer::compareTo)).reversed())
                .collect(Collectors.toList());
        if (!all.isEmpty()) {
            String latestId = all.get(0).getId();
            for (AppVersionClientVO row : all) {
                row.setIsLatest(latestId != null && latestId.equals(row.getId()));
            }
        }
        int p = Math.max(page, 1);
        int ps = Math.min(Math.max(pageSize, 1), 50);
        int from = (p - 1) * ps;
        int to = Math.min(from + ps, all.size());
        List<AppVersionClientVO> slice = from >= all.size() ? List.of() : new ArrayList<>(all.subList(from, to));
        AppVersionListClientVO vo = new AppVersionListClientVO();
        vo.setTotal(all.size());
        vo.setPage(p);
        vo.setPageSize(ps);
        vo.setList(slice);
        return vo;
    }

    /**
     * 检查是否存在高于当前 {@code currentVersionCode} 且匹配端的最新发布。
     */
    public CheckUpdateClientVO check(String currentVersion, int currentVersionCode, String platformRaw) {
        String platform = normalizePlatform(platformRaw);
        List<AppVersionClientVO> newer = clientAppVersionApplicationService.listPublishedForPlatform(platform).stream()
                .map(AppVersionMobileService::toClientVo)
                .filter(v -> v.getVersionCode() != null && v.getVersionCode() > currentVersionCode)
                .sorted(Comparator.comparing(AppVersionClientVO::getVersionCode, Comparator.nullsLast(Integer::compareTo)).reversed())
                .collect(Collectors.toList());
        CheckUpdateClientVO out = new CheckUpdateClientVO();
        if (newer.isEmpty()) {
            out.setHasUpdate(false);
            out.setLatestVersion(null);
            return out;
        }
        AppVersionClientVO latest = newer.get(0);
        latest.setIsLatest(true);
        out.setHasUpdate(true);
        out.setLatestVersion(latest);
        return out;
    }

    /**
     * 将前端/运维多种写法归一为 MINI / H5 / ANDROID / IOS / ALIPAY / UNKNOWN。
     */
    public static String normalizePlatform(String raw) {
        return ClientAppVersionApplicationService.normalizePlatform(raw);
    }

    private static AppVersionClientVO toClientVo(ClientAppVersionReleaseView r) {
        AppVersionClientVO vo = new AppVersionClientVO();
        vo.setId(r.getId());
        vo.setVersion(r.getVersion());
        vo.setVersionCode(r.getVersionCode());
        vo.setReleaseTime(r.getReleaseTime());
        vo.setVersionType(r.getVersionType());
        vo.setVersionTypeName(ClientAppVersionTypeEnum.getDescByValue(r.getVersionType()));
        vo.setUpdateType(r.getUpdateType());
        vo.setUpdateTypeName(ClientAppVersionUpdateStrategyEnum.getDescByValue(r.getUpdateType()));
        vo.setIsLatest(false);
        vo.setDownloadUrl(r.getDownloadUrl());
        vo.setMinVersion(r.getMinVersion());
        AppVersionClientVO.UpdateContentVO uc = new AppVersionClientVO.UpdateContentVO();
        if (r.getUpdateContent() != null) {
            uc.setFeatures(copyList(r.getUpdateContent().getFeatures()));
            uc.setFixes(copyList(r.getUpdateContent().getFixes()));
            uc.setImprovements(copyList(r.getUpdateContent().getImprovements()));
        }
        vo.setUpdateContent(uc);
        return vo;
    }

    private static List<String> copyList(List<String> src) {
        if (src == null) {
            return new ArrayList<>();
        }
        return new ArrayList<>(src);
    }
}
