//go:build ignore

package main

import (
	"fmt"
	"log"
	"os"
	"strings"

	"github.com/glebarez/sqlite"
	"github.com/user-management-system/internal/auth"
	"github.com/user-management-system/internal/config"
	"github.com/user-management-system/internal/domain"
	"gorm.io/gorm"
)

func main() {
	username := strings.TrimSpace(os.Getenv("UMS_ADMIN_USERNAME"))
	password := os.Getenv("UMS_ADMIN_PASSWORD")
	if username == "" {
		username = "admin"
	}

	db, err := gorm.Open(sqlite.Open(resolveDBPath()), &gorm.Config{})
	if err != nil {
		log.Fatal("open db:", err)
	}

	var user domain.User
	if err := db.Where("username = ?", username).First(&user).Error; err != nil {
		log.Fatalf("admin user %q not found: %v", username, err)
	}

	fmt.Printf("admin user: id=%d username=%s status=%d\n", user.ID, user.Username, user.Status)
	if user.Email != nil {
		fmt.Printf("email=%s\n", *user.Email)
	}

	if password == "" {
		fmt.Println("password verification skipped; set UMS_ADMIN_PASSWORD to verify credentials")
		return
	}

	fmt.Printf("password valid: %v\n", auth.VerifyPassword(user.Password, password))
}

func resolveDBPath() string {
	if path := strings.TrimSpace(os.Getenv("UMS_DATABASE_SQLITE_PATH")); path != "" {
		return path
	}

	cfg, err := config.Load(resolveConfigPath())
	if err == nil && strings.EqualFold(strings.TrimSpace(cfg.Database.Type), "sqlite") {
		if path := strings.TrimSpace(cfg.Database.SQLite.Path); path != "" {
			return path
		}
	}

	return "./data/user_management.db"
}

func resolveConfigPath() string {
	if path := strings.TrimSpace(os.Getenv("UMS_CONFIG_PATH")); path != "" {
		return path
	}
	return "./configs/config.yaml"
}
