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"
)

type UserHandler struct {
	userSvc *service.UserService
}

func NewUserHandler(userSvc *service.UserService) *UserHandler {
	return &UserHandler{userSvc: userSvc}
}

func (h *UserHandler) GetMe(w http.ResponseWriter, r *http.Request) {
	userID, ok := middleware.GetUserID(r.Context())
	if !ok {
		utils.WriteError(w, models.ErrAuthRequired)
		return
	}

	user, err := h.userSvc.GetMe(r.Context(), userID)
	if err != nil {
		utils.WriteError(w, err)
		return
	}

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

func (h *UserHandler) UpdateMe(w http.ResponseWriter, r *http.Request) {
	userID, ok := middleware.GetUserID(r.Context())
	if !ok {
		utils.WriteError(w, models.ErrAuthRequired)
		return
	}

	var req struct {
		Timezone                    *string `json:"timezone"`
		WeekStartDay                *int    `json:"week_start_day"`
		DateFormat                  *string `json:"date_format"`
		TimeFormat                  *string `json:"time_format"`
		DefaultEventDurationMinutes *int    `json:"default_event_duration_minutes"`
		DefaultReminderMinutes      *int    `json:"default_reminder_minutes"`
		ShowWeekends                *bool   `json:"show_weekends"`
		WorkingHoursStart           *string `json:"working_hours_start"`
		WorkingHoursEnd             *string `json:"working_hours_end"`
		NotificationsEmail          *bool   `json:"notifications_email"`
	}
	if err := utils.DecodeJSON(r, &req); err != nil {
		utils.WriteError(w, err)
		return
	}

	user, err := h.userSvc.Update(r.Context(), userID, &service.UserUpdateInput{
		Timezone:                    req.Timezone,
		WeekStartDay:                req.WeekStartDay,
		DateFormat:                  req.DateFormat,
		TimeFormat:                  req.TimeFormat,
		DefaultEventDurationMinutes: req.DefaultEventDurationMinutes,
		DefaultReminderMinutes:      req.DefaultReminderMinutes,
		ShowWeekends:                req.ShowWeekends,
		WorkingHoursStart:           req.WorkingHoursStart,
		WorkingHoursEnd:             req.WorkingHoursEnd,
		NotificationsEmail:          req.NotificationsEmail,
	})
	if err != nil {
		utils.WriteError(w, err)
		return
	}

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

func (h *UserHandler) DeleteMe(w http.ResponseWriter, r *http.Request) {
	userID, ok := middleware.GetUserID(r.Context())
	if !ok {
		utils.WriteError(w, models.ErrAuthRequired)
		return
	}

	if err := h.userSvc.Delete(r.Context(), userID); err != nil {
		utils.WriteError(w, err)
		return
	}

	utils.WriteOK(w)
}
