package metastore

import (
	"strings"

	"warpbox/lib/config"
)

func BootstrapAdmin(cfg *config.Config, store *Store) (BootstrapResult, error) {
	adminTag, err := store.EnsureAdminTag()
	if err != nil {
		return BootstrapResult{}, err
	}

	var adminUser *User
	user, ok, err := store.GetUserByUsername(cfg.AdminUsername)
	if err != nil {
		return BootstrapResult{}, err
	}
	if ok {
		if !hasString(user.TagIDs, adminTag.ID) {
			user.TagIDs = append(user.TagIDs, adminTag.ID)
			if err := store.UpdateUser(user); err != nil {
				return BootstrapResult{}, err
			}
		}
		adminUser = &user
	} else if strings.TrimSpace(cfg.AdminPassword) != "" {
		created, err := store.CreateUserWithPassword(cfg.AdminUsername, cfg.AdminEmail, cfg.AdminPassword, []string{adminTag.ID})
		if err != nil {
			return BootstrapResult{}, err
		}
		adminUser = &created
	}

	hasAdminUser, err := store.HasAdminUser(adminTag.ID)
	if err != nil {
		return BootstrapResult{}, err
	}

	return BootstrapResult{
		AdminTag:          adminTag,
		AdminUser:         adminUser,
		AdminLoginEnabled: cfg.AdminLoginEnabled(hasAdminUser),
	}, nil
}

func (store *Store) HasAdminUser(adminTagID string) (bool, error) {
	users, err := store.ListUsers()
	if err != nil {
		return false, err
	}
	for _, user := range users {
		if user.Disabled {
			continue
		}
		if hasString(user.TagIDs, adminTagID) {
			return true, nil
		}
	}
	return false, nil
}

func hasString(values []string, target string) bool {
	for _, value := range values {
		if value == target {
			return true
		}
	}
	return false
}
