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

import json

from django.conf import settings
from django.http import Http404, HttpResponse, JsonResponse
from django.shortcuts import redirect
from django.urls import reverse
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic.base import View

_CHECKOUT_INTENTS = {}


@method_decorator(csrf_exempt, name='dispatch')
class TestHelloAssoOAuth2View(View):
    def post(self, request, *args, **kwargs):
        data = {
            'access_token': 'test_access_token',
            'refresh_token': 'test_refresh_token',
            'expires_in': 3600,
        }
        return JsonResponse(data)


@method_decorator(csrf_exempt, name='dispatch')
class TestHelloAssoCheckoutIntentCreateView(View):
    def post(self, request, *args, **kwargs):
        checkout_intent_id = len(_CHECKOUT_INTENTS) + 1
        body = json.loads(request.body.decode())

        body['backUrl'] = body['backUrl'].replace("https", "http")
        body['returnUrl'] = body['returnUrl'].replace("https", "http")
        body['errorUrl'] = body['errorUrl'].replace("https", "http")

        output_data = {
            'id': checkout_intent_id,
            'redirectUrl': f"{settings.HELLOASSO_TEST_ENDPOINT_URL}"
                           f"{reverse('helloasso-test-redirect-payment', args=(checkout_intent_id,))}",
            'metadata': body['metadata'],
        }

        checkout_intent = {'input': body, 'output': output_data}
        _CHECKOUT_INTENTS[checkout_intent_id] = checkout_intent

        return JsonResponse(output_data)


class TestHelloAssoCheckoutIntentDetailView(View):
    def get(self, request, *args, **kwargs):
        checkout_intent_id = kwargs['checkout_intent_id']
        if checkout_intent_id not in _CHECKOUT_INTENTS:
            raise Http404
        return JsonResponse(_CHECKOUT_INTENTS[checkout_intent_id]['output'])


class TestHelloAssoRedirectPaymentView(View):
    def get(self, request, *args, **kwargs):
        checkout_intent_id = kwargs['checkout_intent_id']
        if checkout_intent_id not in _CHECKOUT_INTENTS:
            raise Http404

        checkout_intent = _CHECKOUT_INTENTS[checkout_intent_id]
        ci_input = checkout_intent['input']
        ci_output = checkout_intent['output']

        if 'error' in request.GET:
            return redirect(ci_input['errorUrl'] + f"&checkoutIntentId={checkout_intent_id}&error=An error occurred.")
        elif 'refused' in request.GET:
            return redirect(ci_input['returnUrl'] + f"&checkoutIntentId={checkout_intent_id}&code=refused")

        dt = timezone.now().isoformat()

        ci_output['order'] = {
            'payer': {
                'email': 'payer@example.com',
                'country': 'FRA',
                'dateOfBirth': '2000-01-01T00:00:00+01:00',
                'firstName': "Payer",
                'lastName': "Payer",
            },
            'items': [
                {
                    'payments': [
                        {
                            'id': checkout_intent_id,
                            'shareAmount': ci_input['totalAmount'],
                        }
                    ],
                    'name': ci_input['itemName'],
                    'priceCategory': 'Fixed',
                    'qrCode': '',
                    'id': checkout_intent_id,
                    'amount': ci_input['totalAmount'],
                    'type': 'Payment',
                    'state': 'Processed'
                }
            ],
            'payments': [
                {
                    'items': [
                        {
                            'id': checkout_intent_id,
                            'shareAmount': ci_input['totalAmount'],
                            'shareItemAmount': ci_input['totalAmount'],
                        }
                    ],
                    'cashOutState': 'MoneyIn',
                    'paymentReceiptUrl': "https://example.com/",
                    'id': checkout_intent_id,
                    'amount': ci_input['totalAmount'],
                    'date': dt,
                    'paymentMeans': 'Card',
                    'installmentNumber': 1,
                    'state': 'Authorized',
                    'meta': {
                        'createdAt': dt,
                        'updatedAt': dt,
                    },
                    'refundOperations': []
                }
            ],
            'amount': {
                'total': ci_input['totalAmount'],
                'vat': 0,
                'discount': 0
            },
            'id': 13339,
            'date': dt,
            'formSlug': 'default',
            'formType': 'Checkout',
            'organizationName': 'Animath',
            'organizationSlug': 'animath',
            'checkoutIntentId': checkout_intent_id,
            'meta': {
                'createdAt': dt,
                'updatedAt': dt,
            },
            'isAnonymous': False,
            'isAmountHidden': False
        }

        return redirect(ci_input['returnUrl'] + f"&checkoutIntentId={checkout_intent_id}&code=succeeded")

    def head(self, request, *args, **kwargs):
        return HttpResponse()