package post

import (
	"context"
	"time"

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

// 发布评论
func AddComment(ctx context.Context, in *pb.CommentItem) (*pb.StatusReply, error) {
	auth, err := service.ParseMetaCtx(ctx, nil)
	if err != nil {
		return nil, err
	}

	var data = models.CmsComment{
		Std_Identity:  types.Std_Identity{Identity: utils.ULID()},
		PostIdentity:  in.PostIdentity,
		OwnerIdentity: auth.Identity,
		Role:          auth.Role,
		ParentId:      uint(in.ParentId),
		ReplyIdentity: in.ReplyIdentity,
		Cms:           in.Cms,
	}
	authName := map[string]any{}
	err = impl.DBService.Table("mall_staff").Take(&authName, "identity=?", auth.Identity).Error
	if err != nil {
		printer.Error(err.Error())
		return nil, errcode.ErrDB
	}
	data.OwnerName = authName["name"].(string)
	err = models.AddComment(&data, auth.Identity)
	if err != nil {
		return nil, err
	}
	return &pb.StatusReply{
		Code:    0,
		Message: vars.OK,
		Details: data.Identity,
		Timeseq: time.Now().Unix(),
	}, nil
}
