package main

import (
	"log"
	"os"
	"strconv"

	"git.pbiernat.dev/egommerce/go-api-pkg/fluentd"
	"git.pbiernat.dev/egommerce/identity-service/internal/app/config"
	"git.pbiernat.dev/egommerce/identity-service/internal/app/database"
	"git.pbiernat.dev/egommerce/identity-service/internal/app/server"
	"github.com/go-redis/redis/v8"
)

const (
	defAppName       = "identity-svc"
	defAppDomain     = "identity-svc"
	defPathPrefix    = "/identity"
	defNetAddr       = ":80"
	defLoggerAddr    = "api-logger:24224"
	defRegistryAddr  = "api-registry:8500"
	defDbURL         = "postgres://postgres:12345678@postgres-db:5432/egommerce"
	defCacheAddr     = "api-cache:6379"
	defCachePassword = "12345678"
	defMongoDbURL    = "mongodb://mongodb:12345678@mongo-db:27017"
	defEventBusURL   = "amqp://guest:guest@api-eventbus:5672"
	ebEventsExchange = "api-events"
	ebEventsQueue    = "identity-svc"
	defKVNmspc       = "dev.egommerce/service/identity-svc"
)

func main() {
	if config.ErrLoadingEnvs != nil {
		log.Panicln("Error loading .env file", config.ErrLoadingEnvs)
	}

	c := new(server.Config)
	c.AppID, _ = os.Hostname()
	c.AppName = config.GetEnv("APP_NAME", defAppName)
	c.AppDomain = config.GetEnv("APP_DOMAIN", defAppDomain)
	c.PathPrefix = config.GetEnv("APP_PATH_PREFIX", defPathPrefix)
	c.NetAddr = config.GetEnv("SERVER_ADDR", defNetAddr)
	c.Port, _ = strconv.Atoi(c.NetAddr[1:])
	c.LoggerAddr = config.GetEnv("LOGGER_ADDR", defLoggerAddr)
	c.RegistryAddr = config.GetEnv("REGISTRY_ADDR", defRegistryAddr)
	c.DbURL = config.GetEnv("DATABASE_URL", defDbURL)
	c.CacheAddr = config.GetEnv("CACHE_ADDR", defCacheAddr)
	c.CachePassword = config.GetEnv("CACHE_PASSWORD", defCachePassword)
	c.EventBusURL = config.GetEnv("EVENTBUS_URL", defEventBusURL)
	c.EventBusExchange = ebEventsExchange
	c.KVNamespace = config.GetEnv("APP_KV_NAMESPACE", defKVNmspc)

	logHost, logPort := fluentd.ParseAddr(c.LoggerAddr)
	logger := fluentd.NewLogger(c.GetAppFullName(), logHost, logPort)
	defer logger.Close()

	// db conn
	dbConn, err := database.Connect(c.DbURL)
	if err != nil { // fixme: add wait-for-db...
		logger.Log("Failed to connect to Database server: %v\n", err)
		os.Exit(1)
	}
	defer dbConn.Close()

	// redis conn
	redis := redis.NewClient(&redis.Options{
		Addr:     c.CacheAddr,
		Password: c.CachePassword,
		DB:       0,
	})
	defer redis.Close()

	// start server
	srv := server.NewServer(c, logger, dbConn, redis /*, ebCh*/)

	forever := make(chan struct{})
	srv.StartWithGracefulShutdown(forever)
	<-forever

	// os.Exit(1)
}
