package user

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

	"gitea.local/admin/hspguard/internal/repository"
	"gitea.local/admin/hspguard/internal/util"
	"github.com/google/uuid"
)

func EnsureAdminUser(ctx context.Context, repo *repository.Queries) {
	adminName := os.Getenv("ADMIN_NAME")
	if adminName == "" {
		adminName = "admin"
	}

	adminEmail := os.Getenv("ADMIN_EMAIL")
	adminPassword := os.Getenv("ADMIN_PASSWORD")

	if adminEmail == "" {
		log.Fatalln("ERR: ADMIN_EMAIL env variable is required")
	}

	_, err := repo.FindUserEmail(ctx, adminEmail)
	if err != nil {
		if adminPassword == "" {
			log.Fatalln("ERR: ADMIN_PASSWORD env variable is required")
		}

		if _, err := createAdmin(ctx, adminName, adminEmail, adminPassword, repo); err != nil {
			log.Fatalln("ERR: Failed to create admin account:", err)
		}
	}
}

func createAdmin(ctx context.Context, name, email, password string, repo *repository.Queries) (uuid.UUID, error) {
	hash, err := util.HashPassword(password)
	if err != nil {
		var id uuid.UUID
		return id, fmt.Errorf("failed to hash the admin password")
	}

	return repo.InsertUser(ctx, repository.InsertUserParams{
		FullName:     name,
		Email:        email,
		PasswordHash: hash,
		IsAdmin:      true,
	})
}
