package http

import (
	"net/http"

	"git.gocasts.ir/ebhomengo/niki/driverapp/service"
	httpmsg "git.gocasts.ir/ebhomengo/niki/pkg/http_msg"
	"github.com/labstack/echo/v4"
)

type Handler struct {
	DriverSvc service.Service
}

func NewHandler(driverSvc service.Service) Handler {
	return Handler{
		DriverSvc: driverSvc,
	}
}

func (h Handler) SendOtp(c echo.Context) error {
	var req service.SendOtpRequest

	if err := c.Bind(&req); err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}

	res, err := h.DriverSvc.SendOtp(c.Request().Context(), req)
	if err != nil {
		msg, code := httpmsg.Error(err)
		return echo.NewHTTPError(code, msg)
	}

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

func (h Handler) loginOrRegister(c echo.Context) error {
	var req service.LoginOrRegisterRequest

	if err := c.Bind(&req); err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}

	res, err := h.DriverSvc.LoginOrRegister(c.Request().Context(), req)
	if err != nil {
		msg, code := httpmsg.Error(err)
		return echo.NewHTTPError(code, msg)
	}

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