package handler

import (
	"engine/internal/iotype"
	"engine/internal/logger"
	"engine/internal/logic"
	"engine/pkg/auxtool/auxhttp"

	"github.com/gin-gonic/gin"
)

type HandlerConfig struct {
	Logic *logic.Logic
}

type Handler struct {
	log *logger.Logger
	lg  *logic.Logic
}

func NewHandler(conf *HandlerConfig) (*Handler, error) {
	var err error
	hand := &Handler{
		log: logger.NewLogger("handler"),
		lg:  conf.Logic,
	}
	return hand, err
}

func (hand *Handler) GetHealth(gctx *gin.Context) {
	var err error
	nReq := &iotype.GetHealthRequest{}
	// Bind request
	err = gctx.ShouldBind(nReq)
	if err != nil {
		hand.log.Errorf("Cannot bind: %v", err)
		auxhttp.SendError(gctx, err)
		return
	}
	// Call logic
	ctx := gctx.Request.Context()
	lgRes, err := hand.lg.GetHealth(ctx, nReq)
	if err != nil {
		hand.log.Errorf("Get error: %v", err)
		auxhttp.SendError(gctx, err)
		return
	}
	// Send result
	nRes := lgRes
	auxhttp.SendResult(gctx, nRes)
}

func (hand *Handler) CreateSession(gctx *gin.Context) {
	var err error
	nReq := &iotype.CreateSessionRequest{}
	// Bind request
	err = gctx.ShouldBind(nReq)
	if err != nil {
		hand.log.Errorf("Cannot bind: %v", err)
		auxhttp.SendError(gctx, err)
		return
	}
	// Call logic
	ctx := gctx.Request.Context()
	lgRes, err := hand.lg.CreateSession(ctx, nReq)
	if err != nil {
		hand.log.Errorf("Get error: %v", err)
		auxhttp.SendError(gctx, err)
		return
	}
	// Send result
	nRes := lgRes
	auxhttp.SendResult(gctx, nRes)
}
