package api

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

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

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

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

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

		if err := svc.RefreshMetadata(ctx, id, mediaType); err != nil {
			slog.Error("refresh metadata failed", "error", err, "media_id", id)
			return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
		}

		return c.JSON(http.StatusOK, map[string]string{"status": "refreshed"})
	}
}

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

		if err := svc.RefreshAllMetadata(ctx); err != nil {
			slog.Error("refresh all metadata failed", "error", err)
			return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
		}

		return c.JSON(http.StatusOK, map[string]string{"status": "refreshing_all"})
	}
}

func serveImage(imageDir string) echo.HandlerFunc {
	return func(c echo.Context) error {
		mediaType := c.Param("type")
		filename := c.Param("filename")

		filePath := filepath.Join(imageDir, mediaType, filename)
		cleanPath := filepath.Clean(filePath)
		cleanBase := filepath.Clean(imageDir)

		if cleanPath == "" || len(cleanPath) < len(cleanBase) || cleanPath[:len(cleanBase)] != cleanBase {
			return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid path"})
		}

		http.ServeFile(c.Response(), c.Request(), filePath)
		return nil
	}
}
