package api

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

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

func listWorkers(scheduler *worker.Scheduler) echo.HandlerFunc {
	return func(c echo.Context) error {
		tasks := scheduler.GetWorkers()
		if tasks == nil {
			tasks = []worker.ScheduledTaskInfo{}
		}
		return c.JSON(http.StatusOK, tasks)
	}
}

func workerHistory(scheduler *worker.Scheduler) echo.HandlerFunc {
	return func(c echo.Context) error {
		name := c.Param("name")

		page, _ := strconv.Atoi(c.QueryParam("page"))
		if page < 1 {
			page = 1
		}
		pageSize, _ := strconv.Atoi(c.QueryParam("page_size"))
		if pageSize < 1 || pageSize > 100 {
			pageSize = 50
		}

		ctx, cancel := context.WithTimeout(c.Request().Context(), 10*time.Second)
		defer cancel()

		executions, total, err := scheduler.GetHistory(ctx, name, page, pageSize)
		if err != nil {
			return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
		}

		if executions == nil {
			executions = []worker.TaskExecution{}
		}

		totalPages := total / pageSize
		if total%pageSize > 0 {
			totalPages++
		}

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

func triggerWorker(scheduler *worker.Scheduler) echo.HandlerFunc {
	return func(c echo.Context) error {
		name := c.Param("name")

		if err := scheduler.TriggerWorker(name); err != nil {
			return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})
		}

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

func updateWorker(scheduler *worker.Scheduler) echo.HandlerFunc {
	return func(c echo.Context) error {
		name := c.Param("name")
		var req struct {
			Enabled *bool `json:"enabled"`
		}
		if err := c.Bind(&req); err != nil {
			return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})
		}
		if req.Enabled == nil {
			return c.JSON(http.StatusBadRequest, map[string]string{"error": "enabled field is required"})
		}
		if err := scheduler.SetEnabled(name, *req.Enabled); err != nil {
			return c.JSON(http.StatusNotFound, map[string]string{"error": err.Error()})
		}
		return c.JSON(http.StatusOK, map[string]string{"status": "updated"})
	}
}
