package main

import (
	"context"
	"fmt"
	"github.com/nats-io/nats.go"
	"madsky.ru/go-tracker/internal/broker"
	"madsky.ru/go-tracker/internal/config"
	"madsky.ru/go-tracker/internal/database"
	"madsky.ru/go-tracker/internal/logger"
	"madsky.ru/go-tracker/internal/server"
	"madsky.ru/go-tracker/internal/storage"
	"os"
)

func main() {
	cfg := config.MustLoad("./config/config.yaml")

	log := logger.NewLogger()
	dsn := getDSN(cfg.Database.Host, cfg.Database.Port, cfg.Database.User, cfg.Database.Password, cfg.Database.Name)

	//ctx := context.WithValue(context.Background(), "value", "foo bar")
	//ctx := context.Background()
	ctx, cancel := context.WithCancel(context.WithValue(context.Background(), "value", "foo bar"))
	defer cancel()

	// broker section
	n := broker.NewBroker(cfg)
	defer n.Close()

	pubErr := n.Publish("test", []byte("foobar"))
	if pubErr != nil {
		fmt.Println(pubErr)
	}
	_, subErr := n.Subscribe("test", func(msg *nats.Msg) {
		fmt.Println(msg.Subject, string(msg.Data))
	})
	if subErr != nil {
		log.Error("Error subscribing", subErr)
	}
	// end broker section

	client, err := database.NewClient(ctx, dsn, log)
	if err != nil {
		log.Error("Error connecting to database", err)
		os.Exit(1)
	}
	defer client.Close()

	store := storage.NewStorage(client)

	app := &server.Application{
		Config:  cfg,
		Storage: store,
		Ctx:     ctx,
	}
	r := app.Routes()

	if err = app.Start(r); err != nil {
		log.Error("Error starting http server", err)
		os.Exit(1)
	}

}

func getDSN(host, port, user, password, name string) string {
	return fmt.Sprintf("host=%s port=%s user=%s password=%s dbname=%s sslmode=disable",
		host, port, user, password, name)
}
