package server

import (
	"html/template"
	"os"
	"path"
	"strings"
	"time"

	"github.com/goccy/go-json"
	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/fiber/v2/middleware/cors"
	"github.com/gofiber/fiber/v2/middleware/logger"
	"github.com/gofiber/template/html/v2"

	"pluja.dev/kycnot.me/config"
	"pluja.dev/kycnot.me/utils/pow"
)

type Server struct {
	ListenAddr    string
	Router        *fiber.App
	PowChallenger *pow.PowChallenger
}

func NewServer(listenAddr string) *Server {
	// Create a new template engine
	engine := html.New(path.Join(os.Getenv("ROOT_DIR"), "frontend/templates"), ".html")
	if config.Conf.Dev {
		engine.Reload(true)
	}

	// Default engine functions
	engine.AddFuncMap(
		map[string]interface{}{
			"attr": func(s string) template.HTMLAttr {
				return template.HTMLAttr(s)
			},
			"safe": func(s string) template.HTML {
				return template.HTML(s)
			},
			"shortText": func(s string) string {
				if len(s) > 50 {
					return strings.TrimSpace(s[:50]) + "..."
				}
				return s
			},
		},
	)

	return &Server{
		ListenAddr: listenAddr,
		Router: fiber.New(fiber.Config{
			JSONEncoder:  json.Marshal,
			JSONDecoder:  json.Unmarshal,
			ReadTimeout:  5 * time.Second,
			WriteTimeout: 10 * time.Second,
			BodyLimit:    2 * 1024 * 1024, // Increase body limit to 2MB
			ServerHeader: "None",          // Optional, for easier debugging
			Views:        engine,
			ViewsLayout:  "base",
		}),
		PowChallenger: &pow.PowChallenger{},
	}
}

func (s *Server) Run() error {
	s.SetupMiddleware()
	s.RegisterRoutes()
	s.PowChallenger.Init()
	return s.Router.Listen(s.ListenAddr)
}

func (s *Server) SetupMiddleware() {
	s.Router.Use(cors.New())

	if config.Conf.Dev {
		s.Router.Use(logger.New())
	}
}

func (s *Server) RegisterRoutes() {
	// Static routes
	s.Router.Static("/static", path.Join(os.Getenv("ROOT_DIR"), "/frontend/static"), fiber.Static{
		Compress:  true,
		ByteRange: true,
	})

	// Register HTTP route for getting initial state.
	s.Router.Get("/", s.handleIndex)
	s.Router.Get("/service/:name", s.handleService)
	s.Router.Get("/point/:id", s.handleAttribute)
	s.Router.Get("/attr/:id", s.handleAttribute)
	s.Router.Get("/request/service", s.handleRequestServiceForm)
	s.Router.Post("/request/service", s.handleRequestServicePostForm)

	// Register API routes
	s.Router.Get("/api/pow/verify/:id/:nonce", s.handleVerifyPow)
}
