package api

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

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

func CreateCategory(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 category model.Category
	err = c.ShouldBindJSON(&category)
	if err != nil {
		log.Error(err)
		return nil, err
	}
	if len(category.Pid) == 0 {
		category.Pid = "top"
	}
	if category.Sort == nil {
		zero := 0
		category.Sort = &zero
	}
	category.CreateTime = time.Now()
	category.UpdateTime = time.Now()
	return repo.RepoAddDoc(apictx.CreateRepoCtx(), repo.CollectionCategory, &category)
}

func DeleteCategory(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.CollectionCategory, _id)
}

func CategoryList(c *gin.Context, apictx *ApiSession) (interface{}, error) {
	page, size, query := UtilQueryPageSize(c)
	return repo.RepoPageSearch(apictx.CreateRepoCtx(), &repo.PageSearchOptions{
		CollectName: repo.CollectionCategory,
		Page:        page,
		Size:        size,
		Query:       query,
		Sort:        bson.D{bson.E{Key: "sort", Value: 1}, bson.E{Key: "createTime", Value: 1}},
	})
}

func UpdateCategory(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 cate model.Category
	err = c.ShouldBindJSON(&cate)
	if err != nil {
		log.Error(err)
		return nil, err
	}
	if cate.Id.IsZero() {
		return nil, errors.New("id错误")
	}
	return repo.RepoUpdateSetDoc(apictx.CreateRepoCtx(), repo.CollectionCategory, cate.Id.Hex(), &cate)
}
