package review

import (
	"context"
	"errors"
	"time"

	"juwan-backend/app/order/rpc/orderservice"
	"juwan-backend/app/player/rpc/playerservice"
	"juwan-backend/app/review/api/internal/svc"
	"juwan-backend/app/review/api/internal/types"
	reviewpb "juwan-backend/app/review/rpc/pb"
)

func formatUnix(ts int64) string {
	if ts <= 0 {
		return ""
	}
	return time.Unix(ts, 0).UTC().Format(time.RFC3339)
}

func toAPIReview(r *reviewpb.Reviews) types.Review {
	return types.Review{
		Id:           r.GetId(),
		OrderId:      r.GetOrderId(),
		FromUserId:   r.GetFromUserId(),
		FromUserName: r.GetFromUserName(),
		Rating:       int(r.GetRating()),
		Content:      r.GetContent(),
		Sealed:       r.GetSealed(),
		CreatedAt:    formatUnix(r.GetCreatedAt()),
	}
}

func orderParticipantUserIDs(ctx context.Context, svcCtx *svc.ServiceContext, order *orderservice.Orders) (int64, int64, error) {
	if order == nil {
		return 0, 0, errors.New("order not found")
	}
	playerResp, err := svcCtx.PlayerRpc.GetPlayersById(ctx, &playerservice.GetPlayersByIdReq{Id: order.GetPlayerId()})
	if err != nil {
		return 0, 0, err
	}
	player := playerResp.GetPlayers()
	if player == nil || player.GetUserId() <= 0 {
		return 0, 0, errors.New("player not found")
	}
	return order.GetConsumerId(), player.GetUserId(), nil
}
