# -*- coding: utf-8 -*-
#
# ITerativ GmbH
# http://www.iterativ.ch/
#
# Copyright (c) 2020 ITerativ GmbH. All rights reserved.
#
# Created on 25.02.20
# @author: chrigu <christian.cueni@iterativ.ch>
import json

from unittest.mock import patch

import requests
from django.test import TestCase, Client
from django.urls import reverse

from core.hep_client import HepClient
from core.tests.mock_hep_data_factory import MockResponse

RESPONSE = {
    'id': 1234,
    'confirmation': 'abdc1234',
    'firstname': 'Pesche',
    'lastname': 'Zubrüti',
    'email': 'aschima@ch.ch',
    'prefix': 'Herr',
    'gender': 1,
    'addresses': [
        {
            'country_id': 'CH',
            'street': ['Weg 1'],
            'postcode': '1234',
            'city': 'Äussere Einöde',
            'firstname': 'Pesche',
            'lastname': 'Zubrüti',
            'prefix': 'Herr',
            'default_shipping': True,
            'default_billing': True,
        }
    ],
}

DATA = {
    'accepted_terms': True,
    'customer': {
        'firstname': 'Pesche',
        'lastname': 'Zubrüti',
        'email': 'aschima@ch.ch',
        'prefix': 'Herr',
        'gender': 1,
        'addresses': [
            {
                'country_id': 'CH',
                'street': ['Weg 1'],
                'postcode': '1234',
                'city': 'Äussere Einöde',
                'firstname': 'Pesche',
                'lastname': 'Zubrüti',
                'prefix': 'Herr',
                'default_shipping': True,
                'default_billing': True,
            }
        ],
        'password': '123454abasfd'
    }
}


class ProxyTest(TestCase):

    def setUp(self):
        self.client = Client()

    @patch.object(HepClient, 'customer_create', return_value=RESPONSE)
    def test_proxy_filters_confirmation_key(self, create_mock):

        response = self.client.post(reverse('api:registration:proxy'), json.dumps(DATA), content_type="application/json")
        found = 'confirmation' in response.json().keys()
        self.assertFalse(found)

    @patch.object(requests, 'post', return_value=MockResponse(400,
      data={'message': 'Ein Kunde mit der gleichen E-Mail-Adresse existiert bereits in einer zugeordneten Website.'}))
    def test_handles_400(self, create_mock):

        response = self.client.post(reverse('api:registration:proxy'), json.dumps(DATA), content_type="application/json")
        self.assertEquals(response.json()['message'], 'Ein Kunde mit der gleichen E-Mail-Adresse existiert bereits in einer zugeordneten Website.')

    def test_requires_accepted_terms(self):

        del DATA['accepted_terms']

        response = self.client.post(reverse('api:registration:proxy'), json.dumps(DATA), content_type="application/json")
        self.assertEquals(response.status_code, 400)
        self.assertEquals(response.json()['message'], 'Sie müssen hier zustimmen, damit Sie sich registrieren können.')
