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 {
	provider rp.RelyingParty
	l        *zap.SugaredLogger
	st       *storage.Storage
}

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

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
	}

	_, 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
	}
	rp.AuthURLHandler(func() string { return requestIDStr }, c.provider).ServeHTTP(w, r)
}
