package oauth

import (
	"crypto/rand"
	"encoding/base64"
	"encoding/json"
	"log"
	"net/http"

	"gitea.local/admin/hspguard/internal/cache"
	"gitea.local/admin/hspguard/internal/util"
	"gitea.local/admin/hspguard/internal/web"
	"github.com/google/uuid"
)

func (h *OAuthHandler) getAuthCode(w http.ResponseWriter, r *http.Request) {
	userId, ok := util.GetRequestUserId(r.Context())
	if !ok {
		web.Error(w, "failed to get user id from auth session", http.StatusInternalServerError)
		return
	}

	user, err := h.repo.FindUserId(r.Context(), uuid.MustParse(userId))
	if err != nil {
		web.Error(w, "user with provided id does not exist", http.StatusUnauthorized)
		return
	}

	type Request struct {
		Nonce    string `json:"nonce"`
		ClientID string `json:"client_id"`
	}

	var req Request

	decoder := json.NewDecoder(r.Body)
	if err := decoder.Decode(&req); err != nil {
		web.Error(w, "nonce field is required in request", http.StatusBadRequest)
		return
	}

	buf := make([]byte, 32)
	_, err = rand.Read(buf)
	if err != nil {
		log.Println("ERR: Failed to generate auth code:", err)
		web.Error(w, "failed to create authorization code", http.StatusInternalServerError)
		return
	}
	authCode := base64.RawURLEncoding.EncodeToString(buf)

	params := cache.SaveAuthCodeParams{
		AuthCode: authCode,
		UserID:   user.ID.String(),
		ClientID: req.ClientID,
		Nonce:    req.Nonce,
	}

	log.Printf("DEBUG: Saving auth code session with params: %#v\n", params)

	if err := h.cache.SaveAuthCode(r.Context(), &params); err != nil {
		log.Println("ERR: Failed to save auth code in redis:", err)
		web.Error(w, "failed to generate auth code", http.StatusInternalServerError)
		return
	}

	type Response struct {
		Code string `json:"code"`
	}

	encoder := json.NewEncoder(w)

	w.Header().Set("Content-Type", "application/json")

	if err := encoder.Encode(Response{
		Code: authCode,
	}); err != nil {
		web.Error(w, "failed to encode response", http.StatusInternalServerError)
	}
}
