// backend/app.go
package main

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

	"scm.bstein.dev/bstein/Pegasus/backend/internal"
)

var serveHTTP = (*http.Server).ListenAndServe

var run = runServer

func runServer() error {
	internal.Logf("PEGASUS_DEBUG=%v, DRY_RUN=%v, TUS_DIR=%s, MEDIA_ROOT=%s", internal.Debug, internal.DryRun, tusDir, mediaRoot)

	if os.Getenv("PEGASUS_SESSION_KEY") == "" {
		return fmt.Errorf("PEGASUS_SESSION_KEY is not set")
	}

	um, err := internal.LoadUserMap(userMapFile)
	if err != nil {
		return fmt.Errorf("load user map: %w", err)
	}
	if internal.Debug {
		keys := make([]string, 0, len(um.Map))
		for k := range um.Map {
			keys = append(keys, k)
		}
		sort.Strings(keys)
		preview := keys
		if len(preview) > 10 {
			preview = preview[:10]
		}
		internal.Logf("user-map loaded (%d): %v%s", len(keys), preview, map[bool]string{true: " ...", false: ""}[len(keys) > len(preview)])
	}

	if err := os.MkdirAll(tusDir, 0o2775); err != nil {
		return fmt.Errorf("mkdir %s: %w", tusDir, err)
	}

	handler := buildRouter(um, jf)
	addr := env("PEGASUS_BIND", ":8080")
	log.Printf("Pegasus listening on %s", addr)

	srv := &http.Server{
		Addr:         addr,
		Handler:      handler,
		ReadTimeout:  0,
		WriteTimeout: 0,
	}
	return serveHTTP(srv)
}
