package auth

import (
	"net/http"

	"git.faercol.me/faercol/polyculeconnect/polyculeconnect/helpers"
	"git.faercol.me/faercol/polyculeconnect/polyculeconnect/internal/storage"
	"github.com/google/uuid"
	"github.com/zitadel/oidc/v3/pkg/client/rp"
	"go.uber.org/zap"
)

const AuthRedirectRoute = "/perform_auth"

type AuthRedirectController struct {
	l  *zap.SugaredLogger
	st *storage.Storage
}

func NewAuthRedirectController(l *zap.SugaredLogger, storage *storage.Storage) *AuthRedirectController {
	return &AuthRedirectController{
		l:  l,
		st: storage,
	}
}

func (c *AuthRedirectController) 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
	}

	backend, err := c.st.LocalStorage.BackendStorage().GetBackendByID(r.Context(), req.BackendID)
	if err != nil {
		c.l.Errorf("Failed to get backend from DB: %s", err)
		helpers.HandleResponse(w, r, http.StatusInternalServerError, []byte("failed to perform auth"), c.l)
		return
	}

	provider, err := rp.NewRelyingPartyOIDC(r.Context(), backend.Config.Issuer, backend.Config.ClientID, backend.Config.ClientSecret, backend.Config.RedirectURI, req.Scopes)
	if err != nil {
		c.l.Errorf("Failed to init relying party: %s", err)
		helpers.HandleResponse(w, r, http.StatusInternalServerError, []byte("failed to perform auth"), c.l)
		return
	}

	rp.AuthURLHandler(func() string { return requestIDStr }, provider).ServeHTTP(w, r)
}
