package logic

import (
	"juwan-backend/app/community/rpc/internal/models"
	"juwan-backend/app/community/rpc/pb"
	"juwan-backend/pkg/types"

	"github.com/jackc/pgx/v5/pgtype"
)

func toTextArray(s []string) types.TextArray {
	if len(s) == 0 {
		return types.TextArray{Elements: []string{}, Valid: true}
	}
	return types.TextArray{
		Elements: s,
		Dims:     []pgtype.ArrayDimension{{Length: int32(len(s)), LowerBound: 1}},
		Valid:    true,
	}
}

func entPostToPb(p *models.Posts) *pb.Posts {
	out := &pb.Posts{
		Id:           p.ID,
		AuthorId:     p.AuthorID,
		AuthorRole:   p.AuthorRole,
		Title:        p.Title,
		Content:      p.Content,
		Images:       p.Images.Elements,
		Tags:         p.Tags.Elements,
		LikeCount:    int64(p.LikeCount),
		CommentCount: int64(p.CommentCount),
		Pinned:       p.Pinned,
		CreatedAt:    p.CreatedAt.Unix(),
		UpdatedAt:    p.UpdatedAt.Unix(),
	}
	if p.LinkedOrderID != nil {
		out.LinkedOrderId = *p.LinkedOrderID
	}
	if p.QuotedPostID != nil {
		out.QuotedPostId = *p.QuotedPostID
	}
	if p.DeletedAt != nil {
		out.DeletedAt = p.DeletedAt.Unix()
	}
	return out
}

func entCommentToPb(c *models.Comments) *pb.Comments {
	out := &pb.Comments{
		Id:        c.ID,
		PostId:    c.PostID,
		AuthorId:  c.AuthorID,
		Content:   c.Content,
		LikeCount: int64(c.LikeCount),
		CreatedAt: c.CreatedAt.Unix(),
	}
	if c.DeletedAt != nil {
		out.DeletedAt = c.DeletedAt.Unix()
	}
	return out
}

func entPostLikeToPb(l *models.PostLikes) *pb.PostLikes {
	return &pb.PostLikes{
		PostId:    l.PostID,
		UserId:    l.UserID,
		CreatedAt: l.CreatedAt.Unix(),
	}
}

func entCommentLikeToPb(l *models.CommentLikes) *pb.CommentLikes {
	return &pb.CommentLikes{
		CommentId: l.CommentID,
		UserId:    l.UserID,
		CreatedAt: l.CreatedAt.Unix(),
	}
}
