package main

import (
	"flag"
	"os"

	"github.com/joho/godotenv"
	"github.com/rs/zerolog"
	"github.com/rs/zerolog/log"

	"pluja.dev/kycnot.me/database"
	"pluja.dev/kycnot.me/server"
)

func main() {
	// Flags
	debug := flag.Bool("debug", false, "sets log level to debug")
	dev := flag.Bool("dev", false, "sets dev mode")
	nocache := flag.Bool("nocache", false, "disables cache")
	flag.Parse()

	// Flags
	log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
	zerolog.SetGlobalLevel(zerolog.InfoLevel)
	if *debug {
		log.Printf("Debug mode enabled")
		log.Logger = log.Output(
			zerolog.ConsoleWriter{
				Out:        os.Stdout,
				TimeFormat: "02.01.2006 15:04:05",
			},
		).With().Caller().Logger()
		zerolog.SetGlobalLevel(zerolog.DebugLevel)
	}
	if *dev {
		log.Logger = log.Output(
			zerolog.ConsoleWriter{
				Out:        os.Stdout,
				TimeFormat: "02.01.2006 15:04:05",
			},
		).With().Caller().Logger()
		zerolog.SetGlobalLevel(zerolog.DebugLevel)
		os.Setenv("DEV_MODE", "true")
		os.Setenv("SCRAPER", "false")
		log.Printf("DEV mode enabled")
	}
	if *nocache {
		log.Printf("Cache disabled")
		os.Setenv("CACHE", "false")
	}

	// Load .env file
	log.Info().Msg("Loading .env file.")
	err := godotenv.Load()
	if err != nil {
		log.Info().Msg("No .env file found, using environment variables")
	}

	// Database init
	log.Info().Msg("Initializing database.")
	database.InitDb()
	defer database.Close()

	// Server init
	log.Info().Msg("Initializing server.")
	server := server.NewServer(os.Getenv("LISTEN_ADDR"))
	server.Run()
}
