package main

import (
	"fmt"
	"net/http"

	"github.com/pingcap/test-infra/services/sdkserver/core"

	"github.com/labstack/echo/v4"
	"github.com/labstack/gommon/log"
)

func SetLogger(next echo.HandlerFunc) echo.HandlerFunc {
	return func(ctx echo.Context) error {
		ctx.SetLogger(log.New(fmt.Sprintf("req: %s", ctx.Response().Header().Get(echo.HeaderXRequestID))))
		return next(ctx)
	}
}

func ResourceErrorHandler(next echo.HandlerFunc) echo.HandlerFunc {
	return func(ctx echo.Context) error {
		err := next(ctx)
		if e, ok := err.(core.Error); ok {
			switch e.Code {
			case core.EInternalError:
				return ctx.String(http.StatusInternalServerError, e.Error())
			case core.EResourceNotFound:
				return ctx.String(http.StatusNotFound, e.Error())
			case core.EMethodNotImplemented:
				return ctx.String(http.StatusMethodNotAllowed, e.Error())
			case core.EGeneralError:
				return ctx.String(http.StatusInternalServerError, e.Error())
			case core.ENotAvailable:
				return ctx.String(http.StatusGone, e.Error())
			}
		}
		return err
	}
}
