package oauth

import (
	"encoding/json"
	"fmt"
	"net/http"

	"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"`
	}

	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
	}

	// TODO: Create real authorization code

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

	encoder := json.NewEncoder(w)

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

	if err := encoder.Encode(Response{
		Code: fmt.Sprintf("%s,%s", user.ID.String(), req.Nonce),
	}); err != nil {
		web.Error(w, "failed to encode response", http.StatusInternalServerError)
	}
}
