#!/bin/bash

# MoneyApp install hooks — pre-flight requirements + Auth.js callback URL.

moneyapp_install_pre()
{
    local app_name="$1"
    # Bail out before any compose/config work if global prerequisites are
    # missing (currently "domain,traefik"). The helper prints what's
    # missing.
    if ! appInstallCheckRequirements "$app_name" "$CFG_MONEYAPP_REQUIRES"; then
        moneyapp=n
        return 1
    fi
}

moneyapp_install_post_compose()
{
    local app_name="$1"

    ((menu_number++))
    echo ""
    echo "---- $menu_number. Resolving Auth.js callback URL (AUTH_URL)."
    echo ""

    # Auth.js requires a fixed AUTH_URL matching what the browser actually
    # hits — otherwise OAuth-style callbacks bounce. Pick:
    #   * https://<host>.<domain>   when traefik is on AND a real domain
    #                                is configured (CFG_DOMAIN_<n>)
    #   * http://<server-ip>:<port> otherwise (raw port exposure)
    local moneyapp_compose_file="$containers_dir$app_name/docker-compose.yml"
    local moneyapp_auth_url=""
    # host_setup is built as `<app>.<domain>` — when CFG_DOMAIN_<n> is
    # empty it ends up as `<app>.`, a valid-but-broken hostname. Reject
    # that explicitly: we want a real TLD before going https.
    local _has_real_domain=0
    if [[ -n "$host_setup" && "$host_setup" != *. ]] && [[ "$host_setup" == *.* ]]; then
        _has_real_domain=1
    fi
    if [[ "$public" == "true" && $_has_real_domain -eq 1 ]]; then
        moneyapp_auth_url="https://$host_setup"
    else
        local moneyapp_port_pair
        moneyapp_port_pair=$(tagsManagerGetTagContent "$moneyapp_compose_file" "PORTS_TAG_1")
        local moneyapp_external_port="${moneyapp_port_pair%%:*}"
        local moneyapp_host="${public_ip_v4:-localhost}"
        moneyapp_auth_url="http://${moneyapp_host}:${moneyapp_external_port}"
        if [[ "$public" == "true" && $_has_real_domain -eq 0 ]]; then
            isNotice "PORT_1 has traefik=true but no domain configured — falling back to direct port URL."
        fi
    fi
    tagsManagerUpdateUniversalTag "$moneyapp_compose_file" "MONEYAPP_AUTH_URL_TAG" "$moneyapp_auth_url"
    isSuccessful "AUTH_URL set to $moneyapp_auth_url"
}
