package handler

import (
	"errors"
	"net/http"
	"strings"

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

// ListReviews godoc
// @Summary List reviews
// @Description Returns reviews. Admins see all, Tenants see only their own.
// @Tags Reviews
// @Security BearerAuth
// @Produce json
// @Param page query int false "Página"
// @Param page_size query int false "Tamanho da página"
// @Success 200 {object} domain.ReviewPage
// @Failure 401 {object} map[string]string
// @Failure 500 {object} map[string]string
// @Router /api/v1/reviews [get]
func (h *Handler) ListReviews(w http.ResponseWriter, r *http.Request) {
	page, pageSize := parsePagination(r)

	requester, err := getRequester(r)
	if err != nil {
		writeError(w, http.StatusUnauthorized, err)
		return
	}

	filter := domain.ReviewFilter{}
	if !strings.EqualFold(requester.Role, "Admin") {
		if requester.CompanyID == nil {
			writeError(w, http.StatusForbidden, errors.New("user has no company associated"))
			return
		}
		// Assuming SellerID logic:
		// Reviews are usually linked to a Seller (Vendor/Pharmacy).
		// If the user is a Tenant/Seller, they should only see reviews where they are the seller.
		filter.SellerID = requester.CompanyID
	}

	result, err := h.svc.ListReviews(r.Context(), filter, page, pageSize)
	if err != nil {
		writeError(w, http.StatusInternalServerError, err)
		return
	}

	writeJSON(w, http.StatusOK, result)
}
