package com.corewing.app.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.corewing.app.entity.AatVersion;
import com.corewing.app.mapper.AatVersionMapper;
import com.corewing.app.service.AatVersionService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * AAT固件版本 Service 实现类
 */
@Service
public class AatVersionServiceImpl extends ServiceImpl<AatVersionMapper, AatVersion> implements AatVersionService {

    @Override
    public AatVersion getLatestByType(String firmwareType) {
        LambdaQueryWrapper<AatVersion> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AatVersion::getFirmwareType, firmwareType);
        wrapper.orderByDesc(AatVersion::getCreateTime);
        wrapper.last("LIMIT 1");
        return getOne(wrapper);
    }

    @Override
    public Map<String, Object> getAllLatestVersions() {
        // 查询所有固件，按类型分组，每组取最新的一条
        List<AatVersion> allVersions = list(
                new LambdaQueryWrapper<AatVersion>().orderByDesc(AatVersion::getCreateTime)
        );

        Map<String, Object> result = new LinkedHashMap<>();
        Map<String, List<AatVersion>> grouped = allVersions.stream()
                .collect(Collectors.groupingBy(AatVersion::getFirmwareType, LinkedHashMap::new, Collectors.toList()));

        for (Map.Entry<String, List<AatVersion>> entry : grouped.entrySet()) {
            Map<String, Object> typeInfo = new HashMap<>();
            List<Map<String, String>> firmwares = new ArrayList<>();
            // 取该类型下最新的一条
            AatVersion latest = entry.getValue().get(0);
            Map<String, String> firmwareInfo = new HashMap<>();
            firmwareInfo.put("firmware_name", latest.getFirmwareName());
            firmwareInfo.put("firmware_version", latest.getFirmwareVersion());
            firmwareInfo.put("min_hardware_version", latest.getMinHardwareVersion());
            firmwares.add(firmwareInfo);
            typeInfo.put("firmwares", firmwares);
            result.put(entry.getKey(), typeInfo);
        }

        return result;
    }
}
