package logic

import (
	"context"
	"errors"

	"juwan-backend/app/community/rpc/internal/models/posts"
	"juwan-backend/app/community/rpc/internal/svc"
	"juwan-backend/app/community/rpc/pb"

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

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

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

func (l *GetPostsByIdLogic) GetPostsById(in *pb.GetPostsByIdReq) (*pb.GetPostsByIdResp, error) {
	if in.GetId() <= 0 {
		return nil, errors.New("id is required")
	}

	post, err := l.svcCtx.CommunityModelRO.Posts.Query().
		Where(posts.IDEQ(in.GetId()), posts.DeletedAtIsNil()).
		First(l.ctx)
	if err != nil {
		return nil, errors.New("post not found")
	}

	return &pb.GetPostsByIdResp{Posts: entPostToPb(post)}, nil
}
