package grpc

import (
	"context"

	activityv1 "hyapp.local/api/proto/activity/v1"
	"hyapp/pkg/appcode"
	"hyapp/pkg/xerr"
	activityservice "hyapp/services/activity-service/internal/service/activity"
)

// Server 把 activity-service 用例层适配为 gRPC 接口。
type Server struct {
	activityv1.UnimplementedActivityServiceServer

	svc *activityservice.Service
}

// NewServer 创建 activity-service gRPC server。
func NewServer(svc *activityservice.Service) *Server {
	return &Server{svc: svc}
}

// PingActivity 返回当前节点同步 RPC 可用性。
func (s *Server) PingActivity(context.Context, *activityv1.PingActivityRequest) (*activityv1.PingActivityResponse, error) {
	nodeID, err := s.svc.Ping()
	if err != nil {
		return nil, xerr.ToGRPCError(err)
	}

	return &activityv1.PingActivityResponse{Ok: true, NodeId: nodeID}, nil
}

// GetActivityStatus 查询活动底座状态。
func (s *Server) GetActivityStatus(ctx context.Context, req *activityv1.GetActivityStatusRequest) (*activityv1.GetActivityStatusResponse, error) {
	ctx = appcode.WithContext(ctx, req.GetMeta().GetAppCode())
	activity, err := s.svc.GetActivityStatus(ctx, req.GetActivityId())
	if err != nil {
		return nil, xerr.ToGRPCError(err)
	}

	return &activityv1.GetActivityStatusResponse{
		ActivityId: activity.ActivityID,
		Status:     string(activity.Status),
	}, nil
}
