package admin

import (
	"errors"
	"net/http"
	"strings"

	"github.com/go-chi/chi/v5"

	"github.com/ultisuite/ulti-backend/internal/api/apiresponse"
	"github.com/ultisuite/ulti-backend/internal/api/apivalidate"
	"github.com/ultisuite/ulti-backend/internal/api/middleware"
	"github.com/ultisuite/ulti-backend/internal/api/query"
)

func (h *Handler) ListPublicShares(w http.ResponseWriter, r *http.Request) {
	params, err := query.ParseListRequest(r)
	if err != nil {
		apivalidate.WriteQueryError(w, r, err)
		return
	}

	result, err := h.svc.ListPublicShares(r.Context(), params)
	if err != nil {
		h.logger.Error("list public shares", "error", err)
		apivalidate.WriteInternal(w, r)
		return
	}
	apiresponse.WriteJSON(w, http.StatusOK, result)
}

func (h *Handler) RevokePublicShare(w http.ResponseWriter, r *http.Request) {
	shareID := strings.TrimSpace(chi.URLParam(r, "shareID"))
	if shareID == "" {
		apivalidate.WriteValidationError(w, r, apivalidate.NewValidationError(
			apivalidate.FieldDetail{Field: "shareID", Message: "required"},
		))
		return
	}
	claims := middleware.ClaimsFromContext(r.Context())
	owner := strings.TrimSpace(r.URL.Query().Get("owner_nc_user_id"))
	if owner == "" {
		apivalidate.WriteValidationError(w, r, apivalidate.NewValidationError(
			apivalidate.FieldDetail{Field: "owner_nc_user_id", Message: "required"},
		))
		return
	}

	if err := h.svc.RevokePublicShare(r.Context(), claims.Sub, shareID, owner); err != nil {
		if errors.Is(err, ErrNotFound) {
			apivalidate.WriteNotFound(w, r, "not found")
			return
		}
		h.logger.Error("revoke public share", "error", err, "share_id", shareID)
		apivalidate.WriteInternal(w, r)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}
