package main

import (
	"context"
	"fmt"
	"log/slog"
	"madsky.ru/go-finance/internal/config"
	"madsky.ru/go-finance/internal/database"
	"madsky.ru/go-finance/internal/server"
	"os"
)

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

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

	//ctx, cancel := context.WithCancel(context.Background())
	//defer cancel()

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

	defer client.Close()
	if err = server.NewServer(ctx, client, logger).Start(); err != nil {
		logger.Error("Error starting http server", err)
		os.Exit(1)
	}

}

func getDSN(host, port, user, password, name string) string {
	//const connUrl = "postgres://postgres:postgres@localhost:5432/go-finance"

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

func NewLogger() *slog.Logger {
	return slog.New(slog.NewJSONHandler(os.Stdout, nil))
}
