package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"gitea.local/admin/hspguard/cmd/hspguard/api"
	"gitea.local/admin/hspguard/internal/cache"
	"gitea.local/admin/hspguard/internal/config"
	"gitea.local/admin/hspguard/internal/repository"
	"gitea.local/admin/hspguard/internal/storage"
	"gitea.local/admin/hspguard/internal/user"
	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/joho/godotenv"
)

func main() {
	err := godotenv.Load()
	if err != nil && os.Getenv("ENV") != "production" {
		log.Fatalln("WARNING: .env file not found. Skipping...")
	}

	var cfg config.AppConfig

	err = config.LoadEnv(&cfg)
	if err != nil {
		log.Fatal(err)
		return
	}

	ctx := context.Background()

	conn, err := pgxpool.New(ctx, cfg.DatabaseURL)
	if err != nil {
		log.Fatalln("ERR: Failed to connect to db:", err)
		return
	}

	repo := repository.New(conn)

	fStorage := storage.New(&cfg)

	cache := cache.NewClient(&cfg)

	user.EnsureAdminUser(ctx, &cfg, repo)

	server := api.NewAPIServer(fmt.Sprintf("%s:%s", cfg.Host, cfg.Port), repo, fStorage, cache, &cfg)
	if err := server.Run(); err != nil {
		log.Fatalln("ERR: Failed to start server:", err)
	}
}
