package api

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

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

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

		items, err := svc.List(ctx)
		if err != nil {
			return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
		}

		return c.JSON(http.StatusOK, map[string]interface{}{"data": items})
	}
}

type createQualityProfileRequest struct {
	Name              string   `json:"name"`
	MediaTypes        []string `json:"media_types"`
	CutoffQuality     string   `json:"cutoff_quality"`
	AllowedQualities  []string `json:"allowed_qualities"`
}

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

		var req createQualityProfileRequest
		if err := c.Bind(&req); err != nil {
			return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})
		}

		if req.Name == "" {
			return c.JSON(http.StatusBadRequest, map[string]string{"error": "name is required"})
		}
		if len(req.MediaTypes) == 0 {
			return c.JSON(http.StatusBadRequest, map[string]string{"error": "media_types is required"})
		}
		if req.CutoffQuality == "" {
			return c.JSON(http.StatusBadRequest, map[string]string{"error": "cutoff_quality is required"})
		}
		if service.GetTierByName(req.CutoffQuality) == nil {
			return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid cutoff_quality tier name"})
		}

		id, err := svc.Create(ctx, req.Name, req.MediaTypes, req.CutoffQuality, req.AllowedQualities)
		if err != nil {
			return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
		}

		return c.JSON(http.StatusCreated, map[string]int64{"id": id})
	}
}

func updateQualityProfile(svc *service.QualityService) echo.HandlerFunc {
	return func(c echo.Context) error {
		ctx, cancel := context.WithTimeout(c.Request().Context(), 5*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"})
		}

		var req service.UpdateQualityProfileRequest
		if err := c.Bind(&req); err != nil {
			return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})
		}

		if err := svc.Update(ctx, id, req); err != nil {
			if err.Error() == "no fields to update" {
				return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})
			}
			if err.Error() == "quality profile not found" {
				return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})
			}
			return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
		}

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

func deleteQualityProfile(svc *service.QualityService) echo.HandlerFunc {
	return func(c echo.Context) error {
		ctx, cancel := context.WithTimeout(c.Request().Context(), 5*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"})
		}

		if err := svc.Delete(ctx, id); err != nil {
			if err.Error() == "quality profile not found" {
				return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})
			}
			return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
		}

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