package main

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

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.InitMessageDB()
	if err != nil {
		log.Fatalf("Could not connect to the database: %v", err)
	}

	// Инициализация репозитория и сервиса
	messageRepo := repositories.NewMessageRepository(db)
	messageService := services.NewMessageService(messageRepo)

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

	// Создаем StreamClient
	streamClient := services.NewStreamClient("http://stream-service:8000", 5*time.Second)

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

	// 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:8080")
	logger.Fatal().Err(http.ListenAndServe(":8080", router)).Msg("Server crashed")
}
