package commerce

import (
	"net/http"
	"strings"

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

func (h *AdminHandler) ActivityRoutes() http.Handler {
	r := chi.NewRouter()
	r.Use(h.auth.RequireRole("admin", "super_admin"))
	r.Get("/options", h.activityOptions)
	r.Get("/", h.listActivities)
	r.Post("/", h.saveActivity)
	r.Put("/{activity_id}", h.saveActivity)
	r.Delete("/{activity_id}", h.deleteActivity)
	return r
}

func (h *Handler) ActivityRoutes() http.Handler {
	r := chi.NewRouter()
	r.Get("/", h.publicActivities)
	r.Get("/{activity_id}", h.publicActivity)
	return r
}

func (h *Handler) publicActivities(w http.ResponseWriter, r *http.Request) {
	status := strings.TrimSpace(r.URL.Query().Get("status"))
	data, err := h.service.ListActivities(r.Context(), status)
	h.writeResult(w, data, err)
}

func (h *Handler) publicActivity(w http.ResponseWriter, r *http.Request) {
	id, ok := parseID(w, chi.URLParam(r, "activity_id"))
	if !ok {
		return
	}
	data, err := h.service.GetActivity(r.Context(), id)
	h.writeResult(w, data, err)
}

func (h *AdminHandler) activityOptions(w http.ResponseWriter, r *http.Request) {
	data, err := h.service.AdminActivityOptions(r.Context())
	h.writeResult(w, data, err)
}

func (h *AdminHandler) listActivities(w http.ResponseWriter, r *http.Request) {
	query := h.query(r)
	if keyword := strings.TrimSpace(r.URL.Query().Get("keyword")); keyword != "" {
		query.Search = keyword
	}
	data, err := h.service.AdminListActivities(r.Context(), query, queryBoolPtr(r.URL.Query().Get("published")))
	h.writeResult(w, data, err)
}

func (h *AdminHandler) saveActivity(w http.ResponseWriter, r *http.Request) {
	id := int64(0)
	if raw := chi.URLParam(r, "activity_id"); raw != "" {
		parsed, ok := parseID(w, raw)
		if !ok {
			return
		}
		id = parsed
	}
	payload := map[string]any{}
	if !decodeAdminJSON(w, r, &payload) {
		return
	}
	adminID, _ := notificationUserID(w, r)
	data, err := h.service.AdminSaveActivity(r.Context(), id, payload, adminID)
	h.writeResult(w, data, err)
}

func (h *AdminHandler) deleteActivity(w http.ResponseWriter, r *http.Request) {
	id, ok := parseID(w, chi.URLParam(r, "activity_id"))
	if !ok {
		return
	}
	data, err := h.service.AdminDeleteActivity(r.Context(), id)
	h.writeResult(w, data, err)
}
