#!/bin/bash
# ==============================================================================
# karch module: user
# Phase 2 (chroot) — Create non-root user, configure sudo, lock root
# ==============================================================================

run_user() {
    msg_info "Setting up user account..."

    # --- Username ------------------------------------------------------------
    local username
    while true; do
        username=$(dialog_input "User Account" \
            "Enter a username for the new account:") || return 1

        # Validate: lowercase, starts with letter, no spaces
        if [[ "$username" =~ ^[a-z][a-z0-9_-]*$ ]]; then
            break
        else
            dialog_msgbox "Invalid Username" \
                "Username must:\n  • Start with a lowercase letter\n  • Contain only lowercase letters, numbers, hyphens, underscores"
        fi
    done

    # --- Password ------------------------------------------------------------
    local password password_confirm
    while true; do
        password=$(dialog_password "Password" \
            "Enter a password for '${username}':") || return 1

        if [[ -z "$password" ]]; then
            dialog_msgbox "Error" "Password cannot be empty."
            continue
        fi

        password_confirm=$(dialog_password "Confirm Password" \
            "Re-enter the password for '${username}':") || return 1

        if [[ "$password" == "$password_confirm" ]]; then
            break
        else
            dialog_msgbox "Mismatch" "Passwords do not match. Please try again."
        fi
    done

    # --- Configure sudo (before creating user, so we can bail safely) -------
    msg_info "Configuring sudo for wheel group..."

    # Uncomment the wheel group line in sudoers
    sed -i 's/^# *%wheel ALL=(ALL:ALL) ALL/%wheel ALL=(ALL:ALL) ALL/' /etc/sudoers

    # Verify sudoers is valid before proceeding
    if ! visudo -c &>/dev/null; then
        msg_error "sudoers validation failed! Reverting..."
        sed -i 's/^%wheel ALL=(ALL:ALL) ALL/# %wheel ALL=(ALL:ALL) ALL/' /etc/sudoers
        return 1
    fi

    # --- Create user (idempotent — safe on retry) ----------------------------
    msg_info "Creating user: $username"
    if id "$username" &>/dev/null; then
        msg_warn "User '$username' already exists — updating password and groups."
        usermod -aG wheel "$username"
    else
        useradd -m -G wheel "$username"
    fi
    echo "${username}:${password}" | chpasswd

    write_env "USERNAME" "$username"

    # --- Lock root account (only after sudo is confirmed working) ------------
    msg_info "Locking root account..."
    passwd -l root

    msg_ok "User '$username' created, sudo configured, root locked."

    dialog_msgbox "User Account" \
        "User created: ${username}\nGroups: wheel (sudo)\n\nThe root account has been locked.\nUse 'sudo' for administrative tasks."

    return 0
}
