package main

import (
	"context"
	"fmt"
	"log/slog"
	"net/http"
	"os"

	"forum-backend/internal/api"
	"forum-backend/internal/config"
	"forum-backend/internal/db"
)

func main() {
	cfg := config.FromEnv()

	ctx := context.Background()
	pool, err := db.NewPool(ctx, cfg.DatabaseURL)
	if err != nil {
		slog.Error("failed to connect to database", "error", err)
		os.Exit(1)
	}
	defer pool.Close()

	if err := db.RunMigrations(ctx, pool); err != nil {
		slog.Error("migrations failed", "error", err)
		os.Exit(1)
	}
	slog.Info("migrations applied", "instance", cfg.InstanceID)

	app := api.NewApp(pool, cfg)
	router := api.BuildRouter(app)

	addr := fmt.Sprintf("0.0.0.0:%d", cfg.Port)
	slog.Info("listening", "addr", addr)
	if err := http.ListenAndServe(addr, router); err != nil {
		slog.Error("server error", "error", err)
		os.Exit(1)
	}
}
