package api

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

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

func listQueue(svc *service.QueueService) 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"))

		items, total, err := svc.List(ctx, service.QueueFilters{
			Status:   c.QueryParam("status"),
			Page:     page,
			PageSize: pageSize,
		})
		if err != nil {
			return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
		}

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

func deleteQueueItem(svc *service.QueueService) 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() == "queue item 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": "cancelled"})
	}
}

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

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

		cancelled, err := svc.BatchDelete(ctx, req)
		if err != nil {
			if err.Error() == "must provide status, batch_id, or ids" {
				return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})
			}
			return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
		}

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

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

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

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

func retryQueueItem(svc *service.QueueService) 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.Retry(ctx, id); err != nil {
			if err.Error() == "queue item not found or not failed" {
				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": "retried"})
	}
}

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

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

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