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

import requests
from django.contrib.sessions.middleware import SessionMiddleware
from django.test import TestCase, RequestFactory
from graphene.test import Client

from api.schema import schema
from core.factories import UserFactory
from oauth.hep_client import HepClient
from users.tests.mock_hep_data_factory import MockResponse, VALID_TEACHERS_ORDERS
from users.models import License, Role, SchoolClass, UserRole


class CouponTests(TestCase):
    def setUp(self):
        Role.objects.create_default_roles()

        self.user = UserFactory(username='aschi@iterativ.ch', email='aschi@iterativ.ch', hep_id=3)
        Role.objects.create_default_roles()
        self.teacher_role = Role.objects.get_default_teacher_role()

        # adding session
        request = RequestFactory().post('/')
        middleware = SessionMiddleware()
        middleware.process_request(request)
        request.user = self.user
        request.session.save()
        self.client = Client(schema=schema, context_value=request)

    def make_coupon_mutation(self, coupon_code, client):
        mutation = '''
            mutation Coupon($input: CouponInput!){
              coupon(input: $input) {
                success
              }
            }
        '''

        return client.execute(mutation, variables={
            'input': {
                'couponCode': coupon_code
            }
        })

    @patch.object(requests, 'put', return_value=MockResponse(200, data=['200', 'Coupon successfully redeemed']))
    @patch.object(HepClient, '_customer_orders', return_value=VALID_TEACHERS_ORDERS)
    @patch.object(HepClient, 'fetch_admin_token', return_value={'token': 'AABBCCDDEE**44566'})
    def test_user_has_valid_coupon(self, admin_mock, orders_mock, response_mock):
        result = self.make_coupon_mutation('COUPON--1234', self.client)

        user_role_key = self.user.user_roles.get(user=self.user).role.key
        self.assertEqual(user_role_key, Role.objects.TEACHER_KEY)
        license = License.objects.get(licensee=self.user)
        self.assertIsNotNone(license)

        school_class = SchoolClass.objects.get(users__in=[self.user])
        self.assertIsNotNone(school_class)

        self.assertTrue(result.get('data').get('coupon').get('success'))
        self.assertTrue(self.user.is_authenticated)

    @patch.object(requests, 'put', return_value=MockResponse(200, data=['201', 'Invalid Coupon']))
    def test_user_has_invalid_coupon(self, response_mock):
        result = self.make_coupon_mutation('COUPON--1234', self.client)

        self.assertEqual(result.get('errors')[0].get('message'), 'invalid_coupon')

    @patch.object(requests, 'put', return_value=MockResponse(200, data=['201', 'Invalid Coupon']))
    def test_unauthenticated_user_cannot_redeem(self, response_mock):

        request = RequestFactory().post('/')
        middleware = SessionMiddleware()
        middleware.process_request(request)
        request.session.save()
        client = Client(schema=schema, context_value=request)

        result = self.make_coupon_mutation('COUPON--1234', client)

        self.assertEqual(result.get('errors')[0].get('message'), 'not_authenticated')
