package auth

import (
	"net/http"

	"git.faercol.me/faercol/polyculeconnect/polyculeconnect/helpers"
	"git.faercol.me/faercol/polyculeconnect/polyculeconnect/internal/storage"
	"github.com/google/uuid"
	"go.uber.org/zap"
)

type AuthDispatchController struct {
	l                *zap.SugaredLogger
	st               *storage.Storage
	redirectHandlers map[uuid.UUID]http.Handler
}

func NewAuthDispatchController(l *zap.SugaredLogger, storage *storage.Storage, redirectHandlers map[uuid.UUID]http.Handler) *AuthDispatchController {
	return &AuthDispatchController{
		l:                l,
		st:               storage,
		redirectHandlers: redirectHandlers,
	}
}

func (c *AuthDispatchController) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	requestIDStr := r.URL.Query().Get("request_id")
	if requestIDStr == "" {
		helpers.HandleResponse(w, r, http.StatusBadRequest, []byte("no request ID in request"), c.l)
		return
	}

	requestID, err := uuid.Parse(requestIDStr)
	if err != nil {
		c.l.Errorf("Invalid UUID format for request ID: %s", err)
		helpers.HandleResponse(w, r, http.StatusBadRequest, []byte("invalid request id"), c.l)
		return
	}

	req, err := c.st.LocalStorage.AuthRequestStorage().GetAuthRequestByID(r.Context(), requestID)
	if err != nil {
		c.l.Errorf("Failed to get auth request from DB: %s", err)
		helpers.HandleResponse(w, r, http.StatusBadRequest, []byte("unknown request id"), c.l)
		return
	}

	loginHandler, ok := c.redirectHandlers[req.BackendID]
	if !ok {
		c.l.Errorf("Backend %s does not exist for request %s", req.ID, req.BackendID)
		helpers.HandleResponse(w, r, http.StatusNotFound, []byte("unknown backend"), c.l)
		return
	}
	loginHandler.ServeHTTP(w, r)
}
