package handlers

import (
	"net/http"

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

type ReminderHandler struct {
	reminderSvc *service.ReminderService
}

func NewReminderHandler(reminderSvc *service.ReminderService) *ReminderHandler {
	return &ReminderHandler{reminderSvc: reminderSvc}
}

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

	var req struct {
		MinutesBefore []int32 `json:"minutes_before"`
	}
	if err := utils.DecodeJSON(r, &req); err != nil {
		utils.WriteError(w, err)
		return
	}

	event, err := h.reminderSvc.AddReminders(r.Context(), userID, eventID, req.MinutesBefore)
	if err != nil {
		utils.WriteError(w, err)
		return
	}

	utils.WriteJSON(w, http.StatusOK, map[string]interface{}{"event": event})
}

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

	if err := h.reminderSvc.DeleteReminder(r.Context(), userID, eventID, reminderID); err != nil {
		utils.WriteError(w, err)
		return
	}

	utils.WriteOK(w)
}
