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"
	"github.com/google/uuid"
)

type AttendeeHandler struct {
	attendeeSvc *service.AttendeeService
}

func NewAttendeeHandler(attendeeSvc *service.AttendeeService) *AttendeeHandler {
	return &AttendeeHandler{attendeeSvc: attendeeSvc}
}

func (h *AttendeeHandler) 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 {
		Attendees []struct {
			UserID *uuid.UUID `json:"user_id"`
			Email  *string    `json:"email"`
		} `json:"attendees"`
	}
	if err := utils.DecodeJSON(r, &req); err != nil {
		utils.WriteError(w, err)
		return
	}

	var addReqs []service.AddAttendeeRequest
	for _, a := range req.Attendees {
		addReqs = append(addReqs, service.AddAttendeeRequest{
			UserID: a.UserID,
			Email:  a.Email,
		})
	}

	event, err := h.attendeeSvc.AddAttendees(r.Context(), userID, eventID, addReqs)
	if err != nil {
		utils.WriteError(w, err)
		return
	}

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

func (h *AttendeeHandler) UpdateStatus(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
	}
	attendeeID, err := utils.ValidateUUID(chi.URLParam(r, "attendeeID"))
	if err != nil {
		utils.WriteError(w, err)
		return
	}

	var req struct {
		Status string `json:"status"`
	}
	if err := utils.DecodeJSON(r, &req); err != nil {
		utils.WriteError(w, err)
		return
	}

	event, err := h.attendeeSvc.UpdateStatus(r.Context(), userID, eventID, attendeeID, req.Status)
	if err != nil {
		utils.WriteError(w, err)
		return
	}

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

func (h *AttendeeHandler) 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
	}
	attendeeID, err := utils.ValidateUUID(chi.URLParam(r, "attendeeID"))
	if err != nil {
		utils.WriteError(w, err)
		return
	}

	if err := h.attendeeSvc.DeleteAttendee(r.Context(), userID, eventID, attendeeID); err != nil {
		utils.WriteError(w, err)
		return
	}

	utils.WriteOK(w)
}
