package community

import (
	"context"
	"strconv"
	"time"

	"juwan-backend/app/community/api/internal/svc"
	"juwan-backend/app/community/api/internal/types"
	communitypb "juwan-backend/app/community/rpc/pb"
	"juwan-backend/app/users/rpc/usercenter"
	"juwan-backend/common/utils/contextj"
)

func currentUserIDOrZero(ctx context.Context) int64 {
	uid, err := contextj.UserIDFrom(ctx)
	if err != nil {
		return 0
	}
	return uid
}

func buildUserProfile(ctx context.Context, svcCtx *svc.ServiceContext, userID int64) types.UserProfile {
	if userID <= 0 {
		return types.UserProfile{}
	}
	resp, err := svcCtx.UserRpc.GetUsersById(ctx, &usercenter.GetUsersByIdReq{Id: userID})
	if err != nil || resp == nil || resp.Users == nil {
		id := strconv.FormatInt(userID, 10)
		return types.UserProfile{Id: id, Username: id, Nickname: "用户" + id, CreatedAt: time.Now().UTC().Format(time.RFC3339)}
	}
	u := resp.Users
	return types.UserProfile{
		Id:        strconv.FormatInt(u.GetId(), 10),
		Username:  u.GetUsername(),
		Nickname:  u.GetNickname(),
		Avatar:    u.GetAvatar(),
		Role:      u.GetCurrentRole(),
		Phone:     u.GetPhone(),
		Bio:       u.GetBio(),
		CreatedAt: time.Unix(u.GetCreatedAt(), 0).UTC().Format(time.RFC3339),
	}
}

func mapPost(ctx context.Context, svcCtx *svc.ServiceContext, p *communitypb.Posts, liked bool) types.Post {
	return types.Post{
		Id:            p.GetId(),
		Title:         p.GetTitle(),
		Content:       p.GetContent(),
		Images:        append([]string(nil), p.GetImages()...),
		Tags:          append([]string(nil), p.GetTags()...),
		LinkedOrderId: p.GetLinkedOrderId(),
		Pinned:        p.GetPinned(),
		LikeCount:     p.GetLikeCount(),
		CommentCount:  p.GetCommentCount(),
		Liked:         liked,
		Author:        buildUserProfile(ctx, svcCtx, p.GetAuthorId()),
		CreatedAt:     time.Unix(p.GetCreatedAt(), 0).UTC().Format(time.RFC3339),
	}
}

func mapComment(ctx context.Context, svcCtx *svc.ServiceContext, c *communitypb.Comments, liked bool) types.Comment {
	return types.Comment{
		Id:        c.GetId(),
		Content:   c.GetContent(),
		Author:    buildUserProfile(ctx, svcCtx, c.GetAuthorId()),
		LikeCount: c.GetLikeCount(),
		Liked:     liked,
		CreatedAt: time.Unix(c.GetCreatedAt(), 0).UTC().Format(time.RFC3339),
	}
}
