package router

import (
	"fmt"
	"io"
	"net/http"
	"os"

	"galaxy/game/internal/router/handler"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
)

const (
	ISO8601 = "2006-01-02 15:04:05.0 -07:00"
)

type Router struct {
	r        *gin.Engine
	executor handler.CommandExecutor
}

func (r Router) Run() error {
	return r.r.Run()
}

func NewRouter() Router {
	gin.SetMode(gin.ReleaseMode)
	return NewRouterExecutor(handler.NewDefaultExecutor())
}

func NewRouterExecutor(executor handler.CommandExecutor) Router {
	return Router{r: setupRouter(executor)}
}

func setupRouter(executor handler.CommandExecutor) *gin.Engine {
	r := gin.New()

	// Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release.
	logConfig := &gin.LoggerConfig{Formatter: logFormatter}
	if gin.Mode() != gin.DebugMode {
		logConfig.Output = io.Discard
	}
	r.Use(gin.LoggerWithConfig(*logConfig))

	// Recovery middleware recovers from any panics and writes a 500 if there was one.
	r.Use(gin.CustomRecovery(recoveryHandler))

	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		if err := v.RegisterValidation("notblank", notBlankStringValidator); err != nil {
			panic(err)
		}
		if err := v.RegisterValidation("ammoWeapons", armamentWithWeaponsValidator); err != nil {
			panic(err)
		}
		if err := v.RegisterValidation("entity", entityNameStringValidator); err != nil {
			panic(err)
		}
		if err := v.RegisterValidation("subject", productionTypeStringValidator); err != nil {
			panic(err)
		}
	}

	r.GET("/healthz", handler.HealthzHandler)

	groupV1 := r.Group("/api/v1")

	groupAdmin := groupV1.Group("/admin")
	groupAdmin.GET("/status", func(ctx *gin.Context) { handler.StatusHandler(ctx, executor) })
	groupAdmin.POST("/init", func(ctx *gin.Context) { handler.InitHandler(ctx, executor) })
	groupAdmin.PUT("/turn", func(ctx *gin.Context) { handler.TurnHandler(ctx, executor) })
	groupAdmin.POST("/race/banish", func(ctx *gin.Context) { handler.BanishHandler(ctx, executor) })

	groupV1.GET("/report", func(ctx *gin.Context) { handler.ReportHandler(ctx, executor) })
	groupV1.PUT("/order", func(ctx *gin.Context) { handler.PutOrderHandler(ctx, executor) })
	groupV1.GET("/order", func(ctx *gin.Context) { handler.GetOrderHandler(ctx, executor) })
	groupV1.GET("/battle/:turn/:uuid", func(ctx *gin.Context) { handler.BattleHandler(ctx, executor) })

	// /command is reserved for future use; any API request for orders should use /order
	groupV1.PUT("/command", LimitMiddleware(1), func(ctx *gin.Context) { handler.CommandHandler(ctx, executor) })

	return r
}

func logFormatter(param gin.LogFormatterParams) string {
	return fmt.Sprintf("[%s] \"%s %s %s %d %s\"\n",
		param.TimeStamp.Format(ISO8601),
		param.Method,
		param.Path,
		param.Request.Proto,
		param.StatusCode,
		param.Latency,
	)
}
func recoveryHandler(c *gin.Context, recovered any) {
	if err, ok := recovered.(string); ok {
		fmt.Fprintf(os.Stderr, "recovered: %s", err)
	}
	c.AbortWithStatus(http.StatusInternalServerError)
}
