package availability

import (
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
)

type Handler struct {
	service *Service
}

func NewHandler(service *Service) *Handler {
	return &Handler{service: service}
}

// SetAvailability godoc
// @Summary      Set availability for a date
// @Tags         availability
// @Accept       json
// @Produce      json
// @Param        request body SetAvailabilityInput true "Availability Input"
// @Success      200  {object}  map[string]string
// @Router       /availability [post]
func (h *Handler) SetAvailability(c *gin.Context) {
	var req SetAvailabilityInput
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	userID := c.GetString("userID") // From middleware
	if userID == "" {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "unauthorized"})
		return
	}

	if err := h.service.SetAvailability(c.Request.Context(), userID, req); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "availability updated"})
}

// ListAvailability godoc
// @Summary      List my availability for a month with ?start=YYYY-MM-DD&end=YYYY-MM-DD
// @Tags         availability
// @Produce      json
// @Param        start query string true "Start Date"
// @Param        end query string true "End Date"
// @Success      200  {array}  map[string]interface{}
// @Router       /availability [get]
func (h *Handler) ListAvailability(c *gin.Context) {
	userId := c.GetString("userID")
	start := c.Query("start")
	end := c.Query("end")

	if start == "" || end == "" {
		// Default to current month
		now := time.Now()
		start = time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC).Format("2006-01-02")
		end = time.Date(now.Year(), now.Month()+1, 0, 0, 0, 0, 0, time.UTC).Format("2006-01-02")
	}

	availabilities, err := h.service.ListMyAvailability(c.Request.Context(), userId, start, end)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// Map to simplify response
	var response []map[string]interface{}
	for _, a := range availabilities {
		response = append(response, map[string]interface{}{
			"date":   a.Data.Time.Format("2006-01-02"),
			"status": a.Status,
		})
	}

	c.JSON(http.StatusOK, response)
}
