package post

import (
	"context"

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

// 获取文章详情 By Key
func GetByKey(ctx context.Context, in *pb.GetPostByKeyRequest) (reply *pb.PostItem, err error) {
	if in.GetKey() == "" {
		return nil, errcode.ErrInvalidArgument
	}

	data, err := models.GetPost("hash", utils.FormatKey(in.Key))
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}

	var res = &pb.PostItem{}
	if data != nil {
		res.Identity = data.Identity
		res.OwnerId = int64(data.OwnerID)
		res.OwnerIdentity = data.OwnerIdentity
		res.Title = data.Title
		res.CoverPath = data.CoverPath
		res.Author = data.Author
		res.AuthorIdentity = data.AuthorIdentity
		res.Content = data.Content
		res.TargetUrl = data.TargetUrl
		res.SourceUrl = data.SourceUrl
		res.Hits = data.Hits
		res.HasAccessory = data.HasAccessory
		res.CreatedAt = data.CreatedAt.String()
		res.UpdatedAt = data.UpdatedAt.String()
		res.Description = data.Description
		res.LikeHits = data.LikeHits
		res.UnlikeHits = data.UnlikeHits
		res.CommentHits = data.CommentHits
		res.PostType = data.Types
		res.Key = data.Hash
		res.Hash = data.Hash
	}
	return res, nil
}
