# Copyright (C) 2010-2024 RhodeCode GmbH
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License, version 3
# (only), as published by the Free Software Foundation.
#
# This program 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 Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
# This program is dual-licensed. If you wish to learn more about the
# RhodeCode Enterprise Edition, including its added features, Support services,
# and proprietary license terms, please see https://rhodecode.com/licenses/

import urllib.parse

from rhodecode.lib.vcs import CurlSession
from rhodecode.lib.ext_json import json
from rhodecode.lib.vcs.exceptions import ImproperlyConfiguredError


def call_service_api(settings, payload):
    try:
        api_host = settings["app.service_api.host"]
        api_token = settings["app.service_api.token"]
        api_url = settings["rhodecode.api.url"]
    except KeyError as exc:
        raise ImproperlyConfiguredError(
            f"{str(exc)} is missing. "
            "Please ensure that app.service_api.host, app.service_api.token and rhodecode.api.url are "
            "defined inside of .ini configuration file."
        )
    payload.update({"id": "service", "auth_token": api_token})
    service_api_url = urllib.parse.urljoin(api_host, api_url)
    response = CurlSession().post(service_api_url, json.dumps(payload))

    if response.status_code != 200:
        raise Exception(f"Service API at {service_api_url} responded with error: {response.status_code}")

    result = json.loads(response.content)["result"]

    return result
