package server

import (
	"fmt"
	"log/slog"
	"net/http"

	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/api"
	"gitlab.com/gitlab-org/cluster-integration/gitlab-agent/v18/internal/gitlab"
	"google.golang.org/grpc"
)

type tunnelHandlerInterface interface {
	tunnel(w http.ResponseWriter, r *http.Request)
}

type tunnelHandler struct {
	log                   *slog.Logger
	gitLabClient          gitlab.ClientInterface
	agentConnPool         func(agentKey api.AgentKey) grpc.ClientConnInterface
	handleProcessingError func(string, error)
}

func newTunnelHandler(log *slog.Logger, gitLabClient gitlab.ClientInterface, agentConnPool func(agentKey api.AgentKey) grpc.ClientConnInterface) *tunnelHandler {
	return &tunnelHandler{
		log:           log,
		gitLabClient:  gitLabClient,
		agentConnPool: agentConnPool,
	}
}

// tunnel handles all workspaces traffic and tunnels them into the appropriate agentw
func (h *tunnelHandler) tunnel(w http.ResponseWriter, r *http.Request) {
	u, err := getUserFromContext(r.Context())
	if err != nil {
		h.handleProcessingError("Failed to get user from context", err)
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return
	}
	workspace, err := getWorkspaceFromContext(r.Context())
	if err != nil {
		h.handleProcessingError("Failed to get workspace from context", err)
		http.Error(w, "Unauthorized", http.StatusUnauthorized)
		return
	}

	message := fmt.Sprintf("Hello from Workspaces Server! Welcome, user:{%v} ! Tunneling your request to workspace:{%v}", u, workspace)
	_, _ = w.Write([]byte(message))
}
