# Copyright (C) 2024 by Animath
# SPDX-License-Identifier: GPL-3.0-or-later

from datetime import datetime, timedelta

from django.conf import settings
import requests

_access_token = None
_refresh_token = None
_expires_at = None


def _get_hello_asso_api_base_url():
    if settings.HELLOASSO_TEST_ENDPOINT:
        return f"{settings.HELLOASSO_TEST_ENDPOINT_URL}/helloasso-test/api"
    elif not settings.DEBUG:
        return "https://api.helloasso.com"
    else:
        return "https://api.helloasso-sandbox.com"


def get_hello_asso_access_token():
    global _access_token, _refresh_token, _expires_at

    base_url = _get_hello_asso_api_base_url()

    now = datetime.now()
    if _access_token is None:
        response = requests.post(
            f"{base_url}/oauth2/token",
            data={
                "grant_type": "client_credentials",
                "client_id": settings.HELLOASSO_CLIENT_ID,
                "client_secret": settings.HELLOASSO_CLIENT_SECRET,
            },
        )
    elif now >= _expires_at:
        response = requests.post(
            f"{base_url}/oauth2/token",
            data={
                "grant_type": "refresh_token",
                "refresh_token": _refresh_token,
            },
        )
    else:
        return _access_token

    if response.status_code == 400:
        raise ValueError(str(response.json()))
    response.raise_for_status()

    data = response.json()
    _access_token = data["access_token"]
    _refresh_token = data["refresh_token"]
    _expires_at = now + timedelta(seconds=data["expires_in"])

    return _access_token


def get_checkout_intent(checkout_id, none_if_link_disabled=False):
    base_url = _get_hello_asso_api_base_url()
    token = get_hello_asso_access_token()

    response = requests.get(
        f"{base_url}/v5/organizations/animath/checkout-intents/{checkout_id}",
        headers={"Authorization": f"Bearer {token}"},
    )
    if response.status_code == 404:
        return None
    elif response.status_code == 400:
        raise ValueError(str(response.json()['errors']))
    response.raise_for_status()

    checkout_intent = response.json()
    if none_if_link_disabled and requests.head(checkout_intent["redirectUrl"]).status_code == 404:
        return None

    return checkout_intent


def create_checkout_intent(amount, name, back_url, error_url, return_url, contains_donation=False, metadata=None):
    base_url = _get_hello_asso_api_base_url()
    token = get_hello_asso_access_token()

    metadata = metadata or {}
    response = requests.post(
        f"{base_url}/v5/organizations/animath/checkout-intents/",
        headers={"Authorization": f"Bearer {token}"},
        json={
            "totalAmount": amount,
            "initialAmount": amount,
            "itemName": name,
            "backUrl": back_url,
            "errorUrl": error_url,
            "returnUrl": return_url,
            "containsDonation": contains_donation,
            "metadata": metadata,
        },
    )
    if response.status_code == 400:
        raise ValueError(str(response.json()['errors']))
    response.raise_for_status()
    return response.json()
