package services

import (
	"context"

	"gitlab.com/gitlab-org/labkit/log"
	spamcheck "gitlab.com/gitlab-org/spamcheck/api/v1"
	"gitlab.com/gitlab-org/spamcheck/app/controllers"
	"gitlab.com/gitlab-org/spamcheck/app/validations"
	"google.golang.org/protobuf/types/known/emptypb"
)

const metricAPICalls string = "spamcheck_api_calls"

type spamCheckService struct {
	Controller  controllers.SpamCheckController
	Validations validations.SpamCheckValidations
	spamcheck.SpamcheckServiceServer
}

// CreateSpamCheckService creates new instances of SpamCheckService
func CreateSpamCheckService(controller controllers.SpamCheckController, validations validations.SpamCheckValidations) spamcheck.SpamcheckServiceServer {

	return &spamCheckService{
		Controller:  controller,
		Validations: validations,
	}
}

// CheckForSpam checks if the Spammable is, in fact, spam
func (s *spamCheckService) CheckForSpamIssue(ctx context.Context, issue *spamcheck.Issue) (*spamcheck.SpamVerdict, error) {
	if err := s.Validations.ValidateIssue(ctx, issue); err != nil {
		return nil, err
	}

	verdict, err := s.Controller.CheckForSpamIssue(ctx, issue)
	log.WithFields(log.Fields{
		"failed": err != nil,
		"method": "CheckForSpamIssue",
		"metric": metricAPICalls,
	}).WithError(err).Info()
	return verdict, err
}

// Healthz handles Kubernetes liveness/readiness probes
// https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/
func (s *spamCheckService) Healthz(ctx context.Context, empty *emptypb.Empty) (*emptypb.Empty, error) {
	return &emptypb.Empty{}, nil
}
