package main

import (
	"fmt"
	"log"
	"log/slog"
	"net/http"
	"os"
	"time"

	"gitea.henriburau.de/haw-lan/cod4watcher/models"
	"gitea.henriburau.de/haw-lan/cod4watcher/routes"
	"gitea.henriburau.de/haw-lan/cod4watcher/services"
	"github.com/go-chi/chi"
	"github.com/joho/godotenv"
)

func main() {
	if err := godotenv.Load(); err != nil {
		log.Fatal(err)
	}

	router := chi.NewMux()

	persistence, err := models.NewSQLitePersistence("local.db")
	if err != nil {
		log.Fatal(err)
	}

	cs := services.NewCaptureService(persistence)
	server := routes.NewServer(cs)

	doneChan := make(chan bool)
	scanner, err := services.NewScanner(persistence, time.Second*10, doneChan)
	if err != nil {
		log.Fatal(err)
	}

	go scanner.Scan()

	router.Use(routes.PathMiddleware)
	router.Handle("/*", public())
	router.Get("/health", routes.Make(server.HandleHealth))
	router.Get("/captures/{captureID}", routes.Make(server.HandleCapture))
	router.Delete("/captures/{captureID}", routes.Make(server.HandleCaptureDelete))
	router.Get("/new/capture", routes.Make(server.HandleCaptureForm))
	router.Post("/new/capture", routes.Make(server.HandleCaptureCreate))
	router.Get("/", routes.Make(server.HandleHome))

	listenAddr := os.Getenv("LISTEN_ADDR")
	slog.Info("HTTP server started", "listenAddr", listenAddr)
	http.ListenAndServe(listenAddr, router)
}

func public() http.Handler {
	fmt.Println("building static files for development")
	return http.StripPrefix("/assets/", http.FileServerFS(os.DirFS("assets")))
}
