package handler

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

	"github.com/gofrs/uuid/v5"
)

// GetSellerDashboard aggregates KPIs for the authenticated seller or the requested company.
// @Summary Dashboard do vendedor
// @Tags Dashboard
// @Security BearerAuth
// @Produce json
// @Param seller_id query string false "Seller ID"
// @Success 200 {object} domain.SellerDashboard
// @Router /api/v1/dashboard/seller [get]
func (h *Handler) GetSellerDashboard(w http.ResponseWriter, r *http.Request) {
	requester, err := getRequester(r)
	if err != nil {
		writeError(w, http.StatusBadRequest, err)
		return
	}

	sellerID := requester.CompanyID
	if sid := r.URL.Query().Get("seller_id"); sid != "" {
		id, err := uuid.FromString(sid)
		if err != nil {
			writeError(w, http.StatusBadRequest, errors.New("invalid seller_id"))
			return
		}
		sellerID = &id
	}

	if sellerID == nil {
		writeError(w, http.StatusBadRequest, errors.New("seller context is required"))
		return
	}

	if !strings.EqualFold(requester.Role, "Admin") && requester.CompanyID != nil && *sellerID != *requester.CompanyID {
		writeError(w, http.StatusForbidden, errors.New("not allowed to view other sellers"))
		return
	}

	dashboard, err := h.svc.GetSellerDashboard(r.Context(), *sellerID)
	if err != nil {
		writeError(w, http.StatusInternalServerError, err)
		return
	}

	writeJSON(w, http.StatusOK, dashboard)
}

// GetAdminDashboard exposes platform-wide aggregated metrics.
// @Summary Dashboard do administrador
// @Tags Dashboard
// @Security BearerAuth
// @Produce json
// @Success 200 {object} domain.AdminDashboard
// @Router /api/v1/dashboard/admin [get]
func (h *Handler) GetAdminDashboard(w http.ResponseWriter, r *http.Request) {
	requester, err := getRequester(r)
	if err != nil {
		writeError(w, http.StatusBadRequest, err)
		return
	}

	if !strings.EqualFold(requester.Role, "Admin") {
		writeError(w, http.StatusForbidden, errors.New("admin role required"))
		return
	}

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

	writeJSON(w, http.StatusOK, dashboard)
}
