package check

import (
	"context"

	"bsm/full/module/base/initial/internal/models"
	pb "bsm/full/module/base/initial/pb"
	"git.apinb.com/bsm-sdk/core/errcode"
	"git.apinb.com/bsm-sdk/core/printer"
)

// 获取应用的相关配置信息
func Config(ctx context.Context, in *pb.ConfigRequest) (reply *pb.ConfigReply, err error) {
	// 输入验证
	if in == nil || in.App == "" || in.Os == "" {
		return nil, errcode.ErrInvalidArgument
	}

	var (
		configs []*models.InitialConfig
		data    []*pb.ConfigItem
	)

	// 查询配置，优先返回特定OS的配置，然后是通用配置
	configs, err = GetConfigByCache(in.App, in.Os)

	if err != nil {
		printer.Error("GetConfigByCache", err)
		return nil, errcode.ErrDB
	}

	// 去重处理：同一个key只保留优先级最高的配置
	configMap := make(map[string]*models.InitialConfig)
	for _, item := range configs {
		if existing, exists := configMap[item.Key]; !exists || item.Os != "ALL" {
			configMap[item.Key] = item
		} else if existing.Os == "ALL" && item.Os != "ALL" {
			configMap[item.Key] = item
		}
	}

	// 转换为响应格式
	for _, item := range configMap {
		data = append(data, &pb.ConfigItem{
			Identity: item.Identity,
			Key:      item.Key,
			Value:    item.Value,
			Version:  item.Version,
		})
	}

	return &pb.ConfigReply{
		Data: data,
	}, nil
}
