package api

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

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

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

		mediaType := c.Param("type")
		if mediaType == "" {
			return c.JSON(http.StatusBadRequest, map[string]string{"error": "media type is required"})
		}

		idStr := c.Param("id")
		id, err := strconv.ParseInt(idStr, 10, 64)
		if err != nil || id <= 0 {
			return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid media id"})
		}

		detail, err := svc.GetFullDetail(ctx, id, mediaType)
		if err != nil {
			if err.Error() == "get media detail: get media: no rows in result set" ||
				strings.Contains(err.Error(), "not found") {
				return c.JSON(http.StatusNotFound, map[string]string{"error": "media not found"})
			}
			slog.Error("get full media detail failed", "id", id, "type", mediaType, "error", err)
			return c.JSON(http.StatusInternalServerError, map[string]string{"error": "failed to fetch media detail"})
		}

		return c.JSON(http.StatusOK, detail)
	}
}
