package main

import (
	"crypto/tls"
	"fmt"
	"log"
	"net/http"

	"git.insit.tech/psa/rtsp_reader-writer/reader/internal/config"
	logger "git.insit.tech/psa/rtsp_reader-writer/reader/internal/log"
	"git.insit.tech/psa/rtsp_reader-writer/reader/internal/metrics"
	"git.insit.tech/psa/rtsp_reader-writer/reader/internal/web/handlers"
	"git.insit.tech/psa/rtsp_reader-writer/reader/internal/web/middlewares"
	"github.com/quic-go/quic-go/http3"
)

func main() {
	go metrics.Metrics()
	logger.StartMainLogger(config.Local, "reader")

	// Check if the data folder in the directory.
	config.DirData = fmt.Sprintf("%s/%s/vod", config.HomeDir, config.Local)
	//
	//err = unpacker.CreateVideo()
	//if err != nil {
	//	logger.Log.Error("failed to create flow", zap.Error(err))
	//}

	config.Storage.Users = make(map[string]config.User)

	mux := http.NewServeMux()

	// Public routes.
	mux.HandleFunc("POST /register", handlers.Register)
	mux.HandleFunc("POST /login", handlers.Login)

	// Authorized routes.
	//authorizedGroup := http.NewServeMux()
	//authorizedGroup.HandleFunc("GET /profile", userHandlerQUIC.Profile)

	// API Flussonic Media Server adapted handlers.
	//mux.HandleFunc("GET /vods/:id/:res/:file", handlersQUIC.SingleVodsHandler)
	//mux.HandleFunc("DELETE /vods/:id/:res/:file", handlersQUIC.DelSingleVodsHandler)
	//mux.HandleFunc("GET /vods/:id/files", handlersQUIC.ListFilesVodsHandler)
	//mux.HandleFunc("DELETE /vods/:id", handlersQUIC.DelVodsHandler)
	//mux.HandleFunc("GET /vods/:id", handlersQUIC.ConfigVodsHandler)
	mux.Handle("GET /vods", middlewares.AuthMiddleware(handlers.ListVodsHandler()))

	// HTTP/1.1 & HTTP/2
	go func() {
		http.ListenAndServeTLS(":8080", config.TLSCertFile, config.TLSKeyFile, mux)

	}()

	server := &http3.Server{
		Addr:      ":8080",
		Handler:   mux,
		TLSConfig: getTLSConfig(),
	}

	log.Fatal(server.ListenAndServe())
}

func getTLSConfig() *tls.Config {
	// Загрузка сертификата и ключа
	cert, err := tls.LoadX509KeyPair(config.TLSCertFile, config.TLSKeyFile)
	if err != nil {
		log.Fatal("Ошибка загрузки сертификата и ключа:", err)
	}

	return &tls.Config{
		Certificates: []tls.Certificate{cert},
		NextProtos:   []string{"h3", "h2", "http/1.1"},
		MinVersion:   tls.VersionTLS13,
	}
}
