package main

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

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

func main() {
	err := godotenv.Load()
	if err != nil {
		log.Fatalln("ERR: Failed to load environment variables:", err)
		return
	}

	ctx := context.Background()

	conn, err := pgx.Connect(ctx, os.Getenv("DATABASE_URL"))
	if err != nil {
		log.Fatalln("ERR: Failed to connect to db:", err)
		return
	}

	repo := repository.New(conn)

	fStorage := storage.New()

	user.EnsureAdminUser(ctx, repo)

	host := os.Getenv("HOST")
	if host == "" {
		host = "127.0.0.1"
	}

	port := os.Getenv("PORT")
	if port == "" {
		port = "3000"
	}

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