package main

import (
	"github.com/gin-gonic/gin"
	"github.com/joho/godotenv"
	_ "github.com/lib/pq"
	"holiday-api/api"
	"holiday-api/db"
	"holiday-api/migration"
	"io/fs"
	"log/slog"
	"net/http"
	"os"
	"runtime/debug"
	"strings"
)

func init() {
	godotenv.Load()
	if !hasProfile("dev") {
		gin.SetMode(gin.ReleaseMode)
	}
	if value := os.Getenv("LOG_FORMAT"); value == "json" {
		slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{AddSource: true})))
	}
}

func main() {
	commit, time := buildInfo()
	slog.Info("build info", slog.String("commit", commit), slog.String("time", time))

	client, err := connectToDb()
	if err != nil {
		slog.Error("couldn't connect to client", slog.String("err", err.Error()))
		os.Exit(1)
	}
	if err := migration.InitializeMigrations(client, migrationFolder()); err != nil {
		slog.Error("couldn't finish migration", slog.String("err", err.Error()))
		os.Exit(1)
	}

	server := api.SetupServer(client)

	port := ":" + getOrDefault("SERVER_PORT", "5281")
	slog.Info("app is ready", slog.String("port", port))
	if err := http.ListenAndServe(port, server); err != nil {
		slog.Error("Couldn't start server!\n", slog.Any("err", err.Error()))
	}
}

func hasProfile(value string) bool {
	profileOptions := strings.Split(os.Getenv("PROFILE"), ",")
	for _, option := range profileOptions {
		if option == value {
			return true
		}
	}
	return false
}

func migrationFolder() fs.FS {
	if hasProfile("dev") {
		return db.DevMigrations
	}
	return db.ProdMigrations
}

func buildInfo() (string, string) {
	revision := ""
	time := ""

	if info, ok := debug.ReadBuildInfo(); ok {
		for _, setting := range info.Settings {
			if setting.Key == "vcs.revision" {
				revision = setting.Value
			} else if setting.Key == "vcs.time" {
				time = setting.Value
			}
		}
	}
	return revision, time
}

func getOrDefault(env string, defaultValue string) string {
	if value, present := os.LookupEnv(env); present {
		return value
	}
	return defaultValue
}
