#!/bin/bash

_mattermostMmctl() {
    sudo docker exec -i mattermost mmctl --local "$@" 2>&1
}

authAdapter_mattermost_setPassword() {
    local user="$1" password="$2"
    [[ -z "$user" ]] && { isError "Username/email is required."; return 1; }
    [[ -z "$password" ]] && password=$(generateRandomPassword)

    local out; out=$(_mattermostMmctl user change-password "$user" --password "$password")
    if [[ $? -ne 0 ]]; then isError "Mattermost reset failed: $out"; return 1; fi

    if [[ "$user" == "${CFG_MATTERMOST_ADMIN_USER:-}" ]]; then
        authPersistCfg mattermost ADMIN_PASSWORD "$password"
    fi
    isSuccessful "Mattermost password set for $user — New password: $password"
}

authAdapter_mattermost_createUser() {
    local user="$1" password="$2" email="$3" isAdmin="$4"
    [[ -z "$user" || -z "$email" ]] && { isError "Username and email are required."; return 1; }
    [[ -z "$password" ]] && password=$(generateRandomPassword)

    local args=(user create --username "$user" --email "$email" --password "$password")
    [[ "$isAdmin" == "true" ]] && args+=(--system-admin)
    local out; out=$(_mattermostMmctl "${args[@]}")
    if [[ $? -ne 0 ]]; then isError "Mattermost create failed: $out"; return 1; fi

    if [[ "$isAdmin" == "true" && -z "${CFG_MATTERMOST_ADMIN_USER:-}" ]]; then
        authPersistCfg mattermost ADMIN_USER "$user"
        authPersistCfg mattermost ADMIN_PASSWORD "$password"
    fi
    isSuccessful "Mattermost user created — User: $user — Email: $email — Password: $password"
}

authAdapter_mattermost_listUsers() {
    _mattermostMmctl user list --json 2>/dev/null \
      | jq -r '.[] | "EZ_USER\t\(.email)\t\(.username)\t\(if .roles | test("system_admin") then "admin" else "user" end)"' 2>/dev/null \
      || _mattermostMmctl user list | awk 'NF>=2 {printf "EZ_USER\t-\t%s\t-\n", $1}'
}

authAdapter_mattermost_deleteUser() {
    local user="$1"
    [[ -z "$user" ]] && { isError "Username/email is required."; return 1; }
    local out; out=$(_mattermostMmctl user delete "$user" --confirm)
    [[ $? -ne 0 ]] && { isError "Mattermost delete failed: $out"; return 1; }
    isSuccessful "Mattermost user '$user' deleted."
}

authAdapter_mattermost_setAdmin() {
    local user="$1" isAdmin="$2"
    [[ -z "$user" ]] && { isError "Username/email is required."; return 1; }
    local sub
    if [[ "$isAdmin" == "true" ]]; then sub="roles system user system_admin"; else sub="roles system user"; fi
    local out; out=$(_mattermostMmctl user $sub "$user" 2>&1)
    [[ $? -ne 0 ]] && { isError "Mattermost role change failed: $out"; return 1; }
    isSuccessful "Mattermost user '$user' admin → $isAdmin."
}
