package main

import (
	"github.com/gorilla/mux"
	"github.com/rs/zerolog"
	httpSwagger "github.com/swaggo/http-swagger"
	"log"
	"net/http"
	"os"
	_ "streamService/docs"
	"streamService/internal/app/database"
	"streamService/internal/app/handlers"
	"streamService/internal/app/repositories"
	"streamService/internal/app/services"
)

func main() {
	// Настройка логирования
	logFile, err := os.OpenFile("app.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
	if err != nil {
		log.Fatalf("Could not open log file: %v", err)
	}
	defer func(logFile *os.File) {
		err := logFile.Close()
		if err != nil {

		}
	}(logFile)

	zerolog.TimeFieldFormat = zerolog.TimeFormatUnix
	logger := zerolog.New(logFile).With().Timestamp().Logger()

	// Инициализация базы данных
	db, err := database.InitStreamDB()
	if err != nil {
		log.Fatalf("Could not connect to the database: %v", err)
	}

	// Инициализация репозитория и сервиса
	streamRepo := repositories.NewStreamRepository(db)
	streamService := services.NewStreamService(streamRepo)

	// Инициализация маршрутизатора
	router := mux.NewRouter()

	// Регистрация хендлеров
	handlers.RegisterStreamRoutes(router, streamService)

	// Swagger
	router.HandleFunc("/doc.json", func(w http.ResponseWriter, r *http.Request) {
		http.ServeFile(w, r, "docs/doc.json")
	}).Methods("GET")

	// Route for Swagger UI
	router.PathPrefix("/swagger/").Handler(httpSwagger.WrapHandler)

	logger.Info().Msg("Server started at http://localhost:8000")
	logger.Fatal().Err(http.ListenAndServe(":8000", router)).Msg("Server crashed")
}
