package analytic

import (
	"net/http"

	svc "git.gocasts.ir/ebhomengo/niki/patientapp/service/analytic"
	richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
	"github.com/labstack/echo/v4"
)

type Handler struct {
	service svc.Service
}

func NewHandler(service svc.Service) *Handler {
	return &Handler{
		service: service,
	}
}

func (h *Handler) Health(e echo.Context) error {
	return e.JSON(http.StatusOK, map[string]interface{}{"status": "ok"})
}

func (h *Handler) PatientsAnalytic(e echo.Context) error {
	var req svc.ListPatientAnalyticRequest

	richErr := richerror.New(richerror.Op("fetchingPatientList.PatientsAnalytic"))

	if err := e.Bind(&req); err != nil {
		richErr = richErr.WithErr(err)
		richErr = richErr.WithKind(1)
		return echo.NewHTTPError(http.StatusBadRequest, richErr)
	}

	response, err := h.service.List(e.Request().Context(), req)
	if err != nil {
		richErr = richErr.WithErr(err)
		richErr = richErr.WithKind(4)
		return echo.NewHTTPError(http.StatusBadRequest, richErr)
	}

	return e.JSON(http.StatusOK, response)
}

func (h *Handler) PatientsMapSummary(e echo.Context) error {
	richErr := richerror.New(richerror.Op("fetchingPatientMapSummary.PatientsMapSummary"))

	var req svc.GetPatientMapSummaryRequest

	if err := e.Bind(&req); err != nil {
		richErr = richErr.WithErr(err)
		richErr = richErr.WithKind(1)
		return echo.NewHTTPError(http.StatusBadRequest, richErr)
	}

	resp, svcErr := h.service.GetMapSummary(e.Request().Context(), req)
	if svcErr != nil {
		richErr = richErr.WithErr(svcErr)
		richErr = richErr.WithKind(4)
		return echo.NewHTTPError(http.StatusBadRequest, richErr)
	}

	return e.JSON(http.StatusOK, resp)
}
