package api

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

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

type importHistoryItem struct {
	ID           int64  `json:"id"`
	MediaID      int64  `json:"media_id"`
	MediaType    string `json:"media_type"`
	Action       string `json:"action"`
	ReleaseTitle string `json:"release_title"`
	Quality      string `json:"quality"`
	CreatedAt    string `json:"created_at"`
}

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

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

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

func listImportHistory(svc *service.ImportService, database *db.DB) 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"))

		var total int
		err := database.Pool.QueryRow(ctx,
			"SELECT COUNT(*) FROM download_history WHERE action = 'import'").Scan(&total)
		if err != nil {
			return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
		}

		offset := (page - 1) * pageSize
		rows, err := database.Pool.Query(ctx,
			`SELECT id, media_id, media_type, action, release_title, quality, created_at
			 FROM download_history WHERE action = 'import'
			 ORDER BY created_at DESC LIMIT $1 OFFSET $2`, pageSize, offset)
		if err != nil {
			return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})
		}
		defer rows.Close()

		var items []importHistoryItem
		for rows.Next() {
			var item importHistoryItem
			var quality []byte
			var createdAt time.Time
			if err := rows.Scan(&item.ID, &item.MediaID, &item.MediaType, &item.Action,
				&item.ReleaseTitle, &quality, &createdAt); err != nil {
				continue
			}
			item.Quality = string(quality)
			item.CreatedAt = createdAt.Format(time.RFC3339)
			items = append(items, item)
		}

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