package handlers

import (
	"net/http"

	"github.com/calendarapi/internal/middleware"
	"github.com/calendarapi/internal/models"
	"github.com/calendarapi/internal/service"
	"github.com/calendarapi/internal/utils"
	"github.com/go-chi/chi/v5"
)

type APIKeyHandler struct {
	apiKeySvc *service.APIKeyService
}

func NewAPIKeyHandler(apiKeySvc *service.APIKeyService) *APIKeyHandler {
	return &APIKeyHandler{apiKeySvc: apiKeySvc}
}

func (h *APIKeyHandler) Create(w http.ResponseWriter, r *http.Request) {
	userID, _ := middleware.GetUserID(r.Context())

	var req struct {
		Name   string              `json:"name"`
		Scopes map[string][]string `json:"scopes"`
	}
	if err := utils.DecodeJSON(r, &req); err != nil {
		utils.WriteError(w, err)
		return
	}

	key, err := h.apiKeySvc.Create(r.Context(), userID, req.Name, req.Scopes)
	if err != nil {
		utils.WriteError(w, err)
		return
	}

	utils.WriteJSON(w, http.StatusOK, key)
}

func (h *APIKeyHandler) List(w http.ResponseWriter, r *http.Request) {
	userID, _ := middleware.GetUserID(r.Context())

	keys, err := h.apiKeySvc.List(r.Context(), userID)
	if err != nil {
		utils.WriteError(w, err)
		return
	}

	utils.WriteList(w, keys, models.PageInfo{Limit: utils.DefaultLimit})
}

func (h *APIKeyHandler) Revoke(w http.ResponseWriter, r *http.Request) {
	userID, _ := middleware.GetUserID(r.Context())
	keyID, err := utils.ValidateUUID(chi.URLParam(r, "id"))
	if err != nil {
		utils.WriteError(w, err)
		return
	}

	if err := h.apiKeySvc.Revoke(r.Context(), userID, keyID); err != nil {
		utils.WriteError(w, err)
		return
	}

	utils.WriteOK(w)
}
