package main

import (
	"net/http"
	"os"
	"path/filepath"
	"strings"

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

func registerAPIRoutes(e *echo.Echo, app *App) {
	api := e.Group("/api")
	api.GET("/health", app.handleHealth)
	api.GET("/state", app.handleGetState)
	api.GET("/events", app.handleEvents)

	api.POST("/admin/login", app.handleAdminLogin)
	api.POST("/admin/logout", app.handleAdminLogout, app.adminOnly)
	api.GET("/admin/state", app.handleGetState, app.adminOnly)
	api.PUT("/admin/settings", app.handleUpdateAdminSettings, app.adminOnly)
	api.POST("/admin/players", app.handleCreatePlayer, app.adminOnly)
	api.POST("/admin/players/auto-group", app.handleAutoGroupPlayers, app.adminOnly)
	api.PUT("/admin/players/:id", app.handleUpdatePlayer, app.adminOnly)
	api.DELETE("/admin/players/:id", app.handleDeletePlayer, app.adminOnly)
	api.PUT("/admin/scores/:stage/:id", app.handleUpdateScore, app.adminOnly)
	api.PUT("/admin/scores/:stage/:id/proof", app.handleUpdateScoreProof, app.adminOnly)
	api.DELETE("/admin/scores/:stage/:id/proof", app.handleDeleteScoreProof, app.adminOnly)
	api.POST("/admin/scores/:stage/:id/advice", app.handleScoreAdvice, app.adminOnly)
	api.POST("/admin/scores/:stage/reset", app.handleResetStageScores, app.adminOnly)
}

func registerWebRoutes(e *echo.Echo, cfg Config) {
	e.GET("/*", func(c echo.Context) error {
		requestPath := strings.TrimPrefix(c.Param("*"), "/")
		if strings.HasPrefix(requestPath, "api") {
			return echo.ErrNotFound
		}

		if requestPath == "" {
			requestPath = "index.html"
		}

		clean := strings.TrimPrefix(filepath.Clean("/"+requestPath), "/")
		assetPath := filepath.Join(cfg.WebDir, clean)
		if stat, err := os.Stat(assetPath); err == nil && !stat.IsDir() {
			return c.File(assetPath)
		}

		indexPath := filepath.Join(cfg.WebDir, "index.html")
		if stat, err := os.Stat(indexPath); err == nil && !stat.IsDir() {
			return c.File(indexPath)
		}

		return c.String(http.StatusNotFound, "frontend build not found. run make build")
	})
}
