package api

import (
	"errors"
	"nrhe-train/db/model"
	"nrhe-train/db/repo"
	"nrhe-train/log"
	"time"

	"github.com/gin-gonic/gin"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

func Version(r *GinRouter) {
	// r.GET("/versions", GetVersion)
	// r.GET("/version/latest", VersionLatest)
	r.POSTJWT("/version/update", UpdateVersion)
	r.POSTJWT("/version/delete/:id", DeleteVersion)
}

// func GetVersion(c *gin.Context, apictx *ApiSession) (interface{}, error) {
// 	page, size, query := UtilQueryPageSize(c)
// 	result, err := repo.RepoPageSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
// 		CollectName: repo.CollectionVersions,
// 		Page:        page,
// 		Size:        size,
// 		Query:       query,
// 		Sort:        bson.M{"createTime": -1},
// 	})
// 	if err != nil {
// 		return nil, err
// 	}
// 	if len(result.List) > 0 {
// 		for _, v := range result.List {
// 			url := v["url"]
// 			v["url"] = fmt.Sprintf("http://%s:%d%s", conf.AppConfig.MasterIp, conf.AppConfig.ServerPort, url)
// 		}
// 	}
// 	return result, nil
// }

// func VersionLatest(c *gin.Context, apictx *ApiSession) (interface{}, error) {
// 	out, err := repo.RepoPageSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
// 		CollectName: repo.CollectionVersions,
// 		Page:        1,
// 		Size:        1,
// 		Sort:        bson.D{bson.E{Key: "createTime", Value: -1}},
// 	})
// 	if err != nil {
// 		return map[string]interface{}{}, nil
// 	}
// 	if len(out.List) < 1 {
// 		return map[string]interface{}{}, nil
// 	}
// 	latestVersion := out.List[0]
// 	url := out.List[0]["url"]
// 	latestVersion["url"] = fmt.Sprintf("http://%s:%d%s", conf.AppConfig.MasterIp, conf.AppConfig.ServerPort, url)
// 	return latestVersion, nil
// }

func UpdateVersion(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	// 验证是否为管理员
	isAdmin, err := IsAdmin(c, apictx)
	if err != nil {
		return nil, err
	}
	if !isAdmin {
		return nil, errors.New("没有权限")
	}
	var version model.Versions
	err = c.ShouldBindJSON(&version)
	if err != nil {
		log.Error(err)
		return nil, err
	}
	if version.Id.IsZero() {
		return nil, errors.New("id错误")
	}
	version.UpdateTime = time.Now()
	return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionVersions, version.Id.Hex(), &version)
}

func DeleteVersion(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	// 验证是否为管理员
	isAdmin, err := IsAdmin(c, apictx)
	if err != nil {
		return nil, err
	}
	if !isAdmin {
		return nil, errors.New("没有权限")
	}
	_id := c.Param("id")
	id, _ := primitive.ObjectIDFromHex(_id)
	if id.IsZero() {
		return nil, errors.New("id错误")
	}
	return repo.RepoDeleteDoc(apictx.CreateRepoCtx(), repo.CollectionVersions, _id)
}
