package check

import (
	"context"

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

// 检查更新
func Updates(ctx context.Context, in *pb.CheckForUpdatesRequest) (reply *pb.CheckForUpdatesReply, err error) {
	// 输入验证
	if in == nil || in.App == "" || in.Os == "" || in.Arch == "" || in.Version == "" {
		return nil, errcode.ErrInvalidArgument
	}

	var data models.InitialApps

	// 查询最新版本
	err = impl.DBService.Where("app = ? AND os = ? AND arch = ?", in.App, in.Os, in.Arch).
		Order("pubdate DESC, id DESC").
		First(&data).Error

	if err != nil {
		if err == gorm.ErrRecordNotFound {
			// 没有找到对应的应用版本
			return &pb.CheckForUpdatesReply{
				Identity: "0",
				Version:  "0",
			}, nil
		}
		return nil, errcode.ErrDB
	}

	// 比较版本号
	if in.Version != data.Version {
		// 有新版本可用
		return &pb.CheckForUpdatesReply{
			Identity: data.Identity,
			Version:  data.Version,
			Summary:  data.Summary,
			Files:    data.Files,
			Pubdate:  data.Pubdate.Format("2006-01-02 15:04:05"),
		}, nil
	}

	// 当前版本是最新的
	return &pb.CheckForUpdatesReply{
		Identity: data.Identity,
		Version:  data.Version,
	}, nil
}
