package web

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

	"backend/internal/auth"
	"backend/internal/db/sqlc"
	"backend/templates"

	"github.com/gorilla/csrf"
)

type PlanningDeps struct {
	Queries *sqlc.Queries
	Now     func() time.Time
}

func parsePlanningStart(raw string, now time.Time) time.Time {
	today := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.Local)
	raw = strings.TrimSpace(raw)
	if raw == "" {
		return today
	}
	parsed, err := time.Parse("2006-01-02", raw)
	if err != nil {
		return today
	}
	return time.Date(parsed.Year(), parsed.Month(), parsed.Day(), 0, 0, 0, 0, time.Local)
}

func PlanningPageHandler(deps PlanningDeps) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		_, user, _ := auth.Authed(r.Context())
		now := time.Now
		if deps.Now != nil {
			now = deps.Now
		}
		start := parsePlanningStart(r.URL.Query().Get("start"), now())
		end := start.AddDate(0, 0, 13)

		rows, err := deps.Queries.ListUserEventsRange(r.Context(), sqlc.ListUserEventsRangeParams{
			UserID:    user.ID,
			StartDate: pgDateFromTime(start),
			EndDate:   pgDateFromTime(end),
		})
		if err != nil {
			slog.Default().Error("planning: ListUserEventsRange failed", "user_id", user.ID, "err", err)
			http.Error(w, "internal server error", http.StatusInternalServerError)
			return
		}

		agenda := templates.NewPlanningAgenda(start, end, parsePlanningStart("", now()), rows)
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		_ = templates.PlanningPage(user, csrf.Token(r), agenda).Render(r.Context(), w)
	}
}
