package auth

import (
	"database/sql"
	"log/slog"
)

func SeedAdmin(db *sql.DB, username, password string) error {
	if username == "" {
		username = "admin"
	}
	if password == "" {
		password = "admin"
	}

	var exists bool
	err := db.QueryRow("SELECT EXISTS(SELECT 1 FROM users WHERE username = ?)", username).Scan(&exists)
	if err != nil {
		return err
	}
	if exists {
		return nil
	}

	hash, err := HashPassword(password)
	if err != nil {
		return err
	}

	_, err = db.Exec(
		"INSERT INTO users (username, password_hash, role) VALUES (?, ?, ?)",
		username, string(hash), "admin",
	)
	if err != nil {
		return err
	}

	slog.Info("admin user created", "username", username)
	return nil
}
