MerchantSetupUri.kt

/*
 * This file is part of GNU Taler
 * (C) 2026 Taler Systems S.A.
 *
 * GNU Taler is free software; you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 3, or (at your option) any later version.
 *
 * GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */

package net.taler.merchantpos.config

import android.net.Uri

internal fun merchantSetupConfig(data: Uri): Config.New?
{
    if (data.scheme != "taler-pos") return null
    val host = data.host?.takeIf(String::isNotBlank) ?: return null
    val authority = if (data.port == -1) host else "$host:${data.port}"
    val pathSegments = data.pathSegments
    val pathStyleInstance =
        pathSegments
            .takeIf { it.size >= 2 && it[0].equals("instances", ignoreCase = true) }
            ?.get(1)
            ?.takeIf(String::isNotBlank)
    val rawFragment =
        data.fragment
            ?.removePrefix("/")
            ?.trim()
            .orEmpty()
    val params =
        rawFragment
            .takeIf { '=' in it }
            ?.split('&')
            ?.associate { part ->
                part.split('=', limit = 2).let { it[0] to Uri.decode(it.getOrElse(1) { "" }) }
            }

    val instance = (pathStyleInstance ?: params?.get("username"))?.takeIf(String::isNotBlank) ?: return null
    val token =
        if (pathStyleInstance != null &&
            params == null)
        {
            Uri.decode(rawFragment).takeIf(String::isNotBlank)
        }
        else
        {
            params?.get("password")?.takeIf(String::isNotBlank)
        } ?: return null

    val merchantUrl =
        Uri
            .Builder()
            .scheme("https")
            .encodedAuthority(authority)
            .appendPath("instances")
            .appendPath(instance)
            .build()
            .toString()

    return Config.New(
        merchantUrl = merchantUrl,
        accessToken = token,
        savePassword = true,
    )
}