package pkiws

import (
	"fmt"
	"log"
	"net/http"

	"git.paulbsd.com/paulbsd/pki/src/config"
	"git.paulbsd.com/paulbsd/pki/src/pki"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

// RunServer runs the main echo HTTP server
func RunServer(cfg *config.Config) (err error) {
	e := echo.New()

	e.Use(middleware.BasicAuth(func(username, password string, c echo.Context) (bool, error) {
		res, user, err := Auth(cfg, username, password, c)
		if res {
			c.Set("username", username)
			c.Set("user", user)
		}
		return res, err
	}))
	e.HideBanner = cfg.Options.HideBanner

	e.GET("/", func(c echo.Context) error {
		return c.String(http.StatusOK, "Welcome to PKI software (https://git.paulbsd.com/paulbsd/pki)")
	})
	e.POST("/cert", func(c echo.Context) (err error) {
		var request EntryRequest
		var result = make(map[string]EntryResponse)
		err = c.Bind(&request)
		if err != nil {
			return c.JSON(http.StatusInternalServerError, "error parsing request")
		}

		log.Printf("Providing %s to user %s at %s\n", request.Domains, c.Get("username"), c.RealIP())

		result, err = GetCertificate(cfg, c.Get("user").(*pki.User), &request.Domains)
		if err != nil {
			return c.String(http.StatusInternalServerError, fmt.Sprintf("%s", err))
		}
		return c.JSON(http.StatusOK, result)
	})

	e.Logger.Fatal(
		e.Start(
			fmt.Sprintf(":%d",
				cfg.Switchs.Port)))

	return
}
