package handler

import (
	"net/http"
	"time"

	"github.com/saveinmed/backend-go/internal/domain"
)

// ListMarketplaceRecords godoc
// @Summary Busca avançada no marketplace
// @Tags Marketplace
// @Produce json
// @Param query query string false "Busca textual"
// @Param sort_by query string false "Campo de ordenação (created_at|updated_at)"
// @Param sort_order query string false "Direção (asc|desc)"
// @Param created_after query string false "Data mínima (RFC3339)"
// @Param created_before query string false "Data máxima (RFC3339)"
// @Param page query integer false "Página"
// @Param page_size query integer false "Itens por página"
// @Success 200 {object} domain.ProductPaginationResponse
// @Router /api/v1/marketplace/records [get]
func (h *Handler) ListMarketplaceRecords(w http.ResponseWriter, r *http.Request) {
	page, pageSize := parsePagination(r)

	req := domain.SearchRequest{
		Query:     r.URL.Query().Get("query"),
		Page:      page,
		PageSize:  pageSize,
		SortBy:    r.URL.Query().Get("sort_by"),
		SortOrder: r.URL.Query().Get("sort_order"),
	}

	if v := r.URL.Query().Get("created_after"); v != "" {
		createdAfter, err := time.Parse(time.RFC3339, v)
		if err != nil {
			writeError(w, http.StatusBadRequest, err)
			return
		}
		req.CreatedAfter = &createdAfter
	}
	if v := r.URL.Query().Get("created_before"); v != "" {
		createdBefore, err := time.Parse(time.RFC3339, v)
		if err != nil {
			writeError(w, http.StatusBadRequest, err)
			return
		}
		req.CreatedBefore = &createdBefore
	}

	result, err := h.svc.ListRecords(r.Context(), req)
	if err != nil {
		writeError(w, http.StatusInternalServerError, err)
		return
	}

	writeJSON(w, http.StatusOK, result)
}
