package web

import (
	"dyproxy/frontend"

	_ "embed"

	"github.com/gofiber/fiber/v3"
	"github.com/gofiber/fiber/v3/middleware/basicauth"
	"github.com/gofiber/fiber/v3/middleware/filesystem"
	"github.com/gofiber/fiber/v3/middleware/redirect"
)

//go:embed ca.crt
var ca []byte

func WithRoutes() Option {
	return func(s *WebServer) {
		apiGroup := s.engine.Group("/api", basicauth.New(basicauth.Config{
			Users: users,
		}))
		apiGroup.Get("/version", s.routeGetVersion)
		apiGroup.Get("/version/file/+", s.routeGetVersionFile)

		apiGroup.Get("/experts", s.routeGetExperts)
		apiGroup.Get("/experts/:uid", s.routeGetExpert)
		apiGroup.Post("/experts", s.routePostExperts)
		apiGroup.Get("/experts/:uid/config", s.routeGetExpertConfig)
		apiGroup.Patch("/experts/:uid/config", s.routePatchExpertConfig)
		apiGroup.Patch("/experts/:uid/state", s.routePatchExpertState)

		apiGroup.Get("/experts/:uid/follower", s.routeGetFollower)
		apiGroup.Post("/followers", s.routePostFollower)

		apiGroup.Get("/devices", s.routeGetDevices)
		apiGroup.Get("/devices/:uuid", s.routeGetDevice)
		apiGroup.Get("/devices/:uuid/follower", s.routeGetDeviceFollower)
		apiGroup.Patch("/devices/:uuid/experts/:uid", s.routeSetDeviceExpert)
		apiGroup.Patch("/devices/:uuid/state", s.routePatchDeviceState)
		apiGroup.Post("/devices/:uuid/block", s.routePatchDeviceState)

		s.engine.Get("/ca", func(c fiber.Ctx) error {
			// send attach ment ca.crt from embeded file
			c.Set(fiber.HeaderContentType, "application/x-x509-ca-cert")
			c.Set(fiber.HeaderContentDisposition, "attachment; filename=ca.crt")
			return c.Send(ca)
		})

		s.engine.Use(redirect.New(redirect.Config{
			Rules:      map[string]string{"/": "/index.html"},
			StatusCode: 301,
		}))

		s.engine.Static("/static", config.Static, fiber.Static{
			Compress:  true,
			ByteRange: true,
			Download:  true,
		})

		s.engine.Use(filesystem.New(filesystem.Config{
			Root:       frontend.Static,
			PathPrefix: "dist",
			Index:      "/dist/index.html",
		}))
	}
}
