package api

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

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

func listMedia(svc *service.MediaService) 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.MediaFilters{
			MediaType: c.QueryParam("type"),
			Status:    c.QueryParam("status"),
			Monitored: c.QueryParam("monitored"),
			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 getMedia(svc *service.MediaService) echo.HandlerFunc {
	return func(c echo.Context) error {
		ctx, cancel := context.WithTimeout(c.Request().Context(), 10*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"})
		}

		detail, err := svc.GetByID(ctx, id, c.Param("type"))
		if err != nil {
			return c.JSON(http.StatusNotFound, map[string]string{"error": "media not found"})
		}

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

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

		var req service.CreateMediaRequest
		if err := c.Bind(&req); err != nil {
			return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})
		}
		if req.Title == "" {
			return c.JSON(http.StatusBadRequest, map[string]string{"error": "title is required"})
		}
		if req.MediaType == "" {
			return c.JSON(http.StatusBadRequest, map[string]string{"error": "media_type is required"})
		}

		id, err := svc.Create(ctx, req)
		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 updateMedia(svc *service.MediaService) 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.UpdateMediaRequest
		if err := c.Bind(&req); err != nil {
			return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})
		}

		if err := svc.Update(ctx, id, c.Param("type"), req); err != nil {
			if err.Error() == "no fields to update" {
				return c.JSON(http.StatusBadRequest, map[string]string{"error": err.Error()})
			}
			if err.Error() == "media 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 deleteMedia(svc *service.MediaService) 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, c.Param("type")); err != nil {
			if err.Error() == "media 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"})
	}
}

func searchMedia(svc *service.MediaService) 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.Search(ctx, service.MediaFilters{
			Query:     c.QueryParam("q"),
			MediaType: c.QueryParam("type"),
			Status:    c.QueryParam("status"),
			Tag:       c.QueryParam("tag"),
			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 searchMissing(svc *service.MediaService) 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.SearchMissing(ctx, service.MediaFilters{
			MediaType: c.QueryParam("type"),
			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 searchUpgrades(svc *service.MediaService) 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.SearchUpgrades(ctx, service.MediaFilters{
			MediaType: c.QueryParam("type"),
			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),
		})
	}
}
