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 SharingHandler struct {
	calSvc *service.CalendarService
}

func NewSharingHandler(calSvc *service.CalendarService) *SharingHandler {
	return &SharingHandler{calSvc: calSvc}
}

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

	var req struct {
		Target struct {
			Email string `json:"email"`
		} `json:"target"`
		Role string `json:"role"`
	}
	if err := utils.DecodeJSON(r, &req); err != nil {
		utils.WriteError(w, err)
		return
	}

	if err := h.calSvc.Share(r.Context(), userID, calID, req.Target.Email, req.Role); err != nil {
		utils.WriteError(w, err)
		return
	}

	utils.WriteOK(w)
}

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

	members, err := h.calSvc.ListMembers(r.Context(), userID, calID)
	if err != nil {
		utils.WriteError(w, err)
		return
	}

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

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

	if err := h.calSvc.RemoveMember(r.Context(), userID, calID, targetID); err != nil {
		utils.WriteError(w, err)
		return
	}

	utils.WriteOK(w)
}
