package api

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

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

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

		page, pageSize := service.ParsePagination(c.QueryParam("page"), c.QueryParam("page_size"))

		var mediaID *int64
		if mid := c.QueryParam("media_id"); mid != "" {
			if id, err := strconv.ParseInt(mid, 10, 64); err == nil {
				mediaID = &id
			}
		}

		events, total, err := svc.List(ctx, service.ActivityFilters{
			EventType: c.QueryParam("event_type"),
			MediaID:   mediaID,
			MediaType: c.QueryParam("media_type"),
			Page:      page,
			PageSize:  pageSize,
		})
		if err != nil {
			slog.Error("failed to list activity", "error", err)
			return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
		}

		return c.JSON(http.StatusOK, paginatedResponse{
			Data:       events,
			Total:      total,
			Page:       page,
			PageSize:   pageSize,
			TotalPages: service.CalcTotalPages(total, pageSize),
		})
	}
}
