package routers

import (
	"context"
	"fmt"
	"net/http"
	"strings"

	"git.paulbsd.com/paulbsd/ipbl/src/config"
	"github.com/labstack/echo/v4"
)

func RunServer(ctx *context.Context, cfg *config.Config) (err error) {
	e := echo.New()
	e.HideBanner = true

	RegisterRoutes(e, ctx, cfg)
	err = e.Start(
		fmt.Sprintf(":%d",
			cfg.Switchs.Port))

	return
}

func Result(c echo.Context, inputerr error, data interface{}) (err error) {
	if inputerr != nil {
		if inputerr.Error() == "Not Found" {
			return c.String(http.StatusNotFound, "Content not found")
		}
		if strings.Contains(inputerr.Error(), "duplicate key value violates unique constraint") {
			return c.String(http.StatusConflict, "Content already exists")
		}
		if strings.Contains(inputerr.Error(), "already exists") {
			return c.String(http.StatusConflict, "Content already exists")
		}
		if inputerr.Error() == "Error when parsing body" {
			return c.String(http.StatusBadRequest, "Content not conform")
		}
		return c.String(http.StatusInternalServerError, inputerr.Error())
	}
	return c.JSON(http.StatusOK, data)
}

func ConfigAccess(cfg config.Config, ip string) (ret bool) {
	switch ip {
	case "127.0.0.1":
		return true
	case "::1":
		return true
	default:
		return
	}
}
