package client

import (
	"context"

	"google.golang.org/grpc"
	userv1 "hyapp.local/api/proto/user/v1"
	"hyapp/pkg/appcode"
	messageservice "hyapp/services/activity-service/internal/service/message"
)

// GRPCRoleInvitationClient calls user-service because role invitation state remains owned by user-service.
type GRPCRoleInvitationClient struct {
	client userv1.UserHostServiceClient
}

func NewGRPCRoleInvitationClient(conn *grpc.ClientConn) *GRPCRoleInvitationClient {
	return &GRPCRoleInvitationClient{client: userv1.NewUserHostServiceClient(conn)}
}

func (c *GRPCRoleInvitationClient) ProcessRoleInvitation(ctx context.Context, input messageservice.ProcessRoleInvitationInput) (messageservice.RoleInvitationState, error) {
	resp, err := c.client.ProcessRoleInvitation(ctx, &userv1.ProcessRoleInvitationRequest{
		Meta: &userv1.RequestMeta{
			RequestId: "message-action-confirm-process-role-invitation",
			Caller:    "activity-service",
			AppCode:   appcode.FromContext(ctx),
		},
		CommandId:    input.CommandID,
		ActorUserId:  input.ActorUserID,
		InvitationId: input.InvitationID,
		Action:       input.Action,
		Reason:       input.Reason,
	})
	if err != nil {
		return messageservice.RoleInvitationState{}, err
	}
	return roleInvitationStateFromProto(resp.GetInvitation()), nil
}

func (c *GRPCRoleInvitationClient) GetRoleInvitation(ctx context.Context, actorUserID int64, invitationID int64) (messageservice.RoleInvitationState, error) {
	resp, err := c.client.GetRoleInvitation(ctx, &userv1.GetRoleInvitationRequest{
		Meta: &userv1.RequestMeta{
			RequestId: "message-action-confirm-get-role-invitation",
			Caller:    "activity-service",
			AppCode:   appcode.FromContext(ctx),
		},
		ActorUserId:  actorUserID,
		InvitationId: invitationID,
	})
	if err != nil {
		return messageservice.RoleInvitationState{}, err
	}
	return roleInvitationStateFromProto(resp.GetInvitation()), nil
}

func roleInvitationStateFromProto(invitation *userv1.RoleInvitation) messageservice.RoleInvitationState {
	if invitation == nil {
		return messageservice.RoleInvitationState{}
	}
	return messageservice.RoleInvitationState{
		InvitationID:   invitation.GetInvitationId(),
		InvitationType: invitation.GetInvitationType(),
		Status:         invitation.GetStatus(),
	}
}
