package api

import (
	"context"
	"log/slog"
	"net/http"
	"time"

	"github.com/TopherMayor/unified-media-manager/internal/service"
	"github.com/labstack/echo/v4"
)

type calendarResponse struct {
	Data  []service.CalendarEvent `json:"data"`
	Month string                  `json:"month"`
}

func listCalendarEvents(svc *service.CalendarService) echo.HandlerFunc {
	return func(c echo.Context) error {
		ctx, cancel := context.WithTimeout(c.Request().Context(), 10*time.Second)
		defer cancel()

		monthParam := c.QueryParam("month")
		if monthParam == "" {
			now := time.Now()
			monthParam = now.Format("2006-01")
		}

		parsed, err := time.Parse("2006-01", monthParam)
		if err != nil {
			return c.JSON(http.StatusBadRequest, map[string]string{"error": "month must be in YYYY-MM format"})
		}

		events, err := svc.EventsByMonth(ctx, parsed.Year(), parsed.Month())
		if err != nil {
			slog.Error("calendar events failed", "month", monthParam, "error", err)
			return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to fetch calendar events"})
		}

		return c.JSON(http.StatusOK, calendarResponse{
			Data:  events,
			Month: monthParam,
		})
	}
}
