package logic

import (
	"context"

	plantModel "sundynix-micro-go/app/plant/model"
	"sundynix-micro-go/app/plant/rpc/internal/svc"
	"sundynix-micro-go/app/plant/rpc/plant"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetPostDetailLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetPostDetailLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetPostDetailLogic {
	return &GetPostDetailLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 帖子详情
func (l *GetPostDetailLogic) GetPostDetail(in *plant.IdReq) (*plant.PostDetailResp, error) {
	var post plantModel.Post
	if err := l.svcCtx.DB.Where("id = ?", in.Id).First(&post).Error; err != nil {
		return nil, err
	}
	var comments []plantModel.PostComment
	l.svcCtx.DB.Where("post_id = ?", in.Id).Order("created_at asc").Find(&comments)

	var commentInfos []*plant.PostCommentInfo
	for _, c := range comments {
		commentInfos = append(commentInfos, &plant.PostCommentInfo{
			Id:        c.ID,
			UserId:    c.UserID,
			Content:   c.Content,
			ParentId:  c.ParentID,
			CreatedAt: c.CreatedAt.Unix(),
		})
	}
	return &plant.PostDetailResp{
		Post: &plant.PostInfo{
			Id:           post.ID,
			UserId:       post.UserID,
			Title:        post.Title,
			Content:      post.Content,
			ViewCount:    int32(post.ViewCount),
			CommentCount: int32(post.CommentCount),
			LikeCount:    int32(post.LikeCount),
			Location:     post.Location,
			CreatedAt:    post.CreatedAt.Unix(),
		},
		Comments: commentInfos,
	}, nil
}
