package server

import (
	"context"
	"log/slog"

	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/autoflow/engine"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/autoflow/rpc"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/module/modserver"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type server struct {
	rpc.UnsafeAutoFlowServer
	log       *slog.Logger
	serverAPI modserver.API
	flowEng   *engine.Engine
}

func (s *server) CloudEvent(ctx context.Context, req *rpc.CloudEventRequest) (*rpc.CloudEventResponse, error) {
	ctx = context.WithValue(ctx, contextPropagatorKey, &contextPropagatorValues{
		ProjectID: req.FlowProject.Id,
		EventID:   req.Event.Id,
		EventType: req.Event.Type,
	})

	err := s.flowEng.HandleEvent(ctx, &engine.HandleEventRequest{
		Event:       req.Event,
		FlowProject: req.FlowProject,
		Variables:   req.Variables,
	})
	if err != nil {
		// TODO proper error status
		s.serverAPI.HandleProcessingError(ctx, s.log, "Error handling event", err)
		return nil, status.Errorf(codes.Unavailable, "Error handling event: %v", err)
	}
	return &rpc.CloudEventResponse{}, nil
}
