import django
from django.conf import settings
from django.http import Http404
from django.template.response import TemplateResponse
from django.test import SimpleTestCase
from django.test import override_settings
from django.test.client import RequestFactory
from mock.mock import patch
from rest_framework import status

from haso_payment.tests.mixins import MockResponseMixin

if not settings.configured:
    settings.configure()


@override_settings(
    PZ_SERVICE_CLASS="haso_payment.commerce.dummy.Service",
    HASO_EXTENSION_CONF={
        "default": {
            "extension_url": "https://your-extension.url",
            "hash_key": "your-extension-hash-key",
        }
    }
)
class TestHasoPaymentRedirectView(SimpleTestCase, MockResponseMixin):
    def setUp(self):
        from haso_payment.views import HasoPaymentView
        django.setup()
        self.view = HasoPaymentView
        self.request_factory = RequestFactory()

    @override_settings(HASO_EXTENSION_URL=None)
    def test_none_payment_extension_url(self):
        request = self.request_factory.get("/payment-gateway/haso/")
        request.GET = {"sessionid": "test-session-id"}
        with self.assertRaises(Http404):
            self.view.as_view()(request)

    @patch("haso_payment.commerce.dummy.Service.get")
    def test_none_pre_order(self, mock_get):
        response = self._mock_response(
            status_code=200,
            content={},
            headers={"Content-Type": "application/json"},
        )
        mock_get.return_value = response

        request = self.request_factory.get("/payment-gateway/haso/")
        request.GET = {"sessionId": "test-session-id"}
        with self.assertRaises(Http404):
            self.view.as_view()(request)

    @patch("haso_payment.commerce.dummy.Service.get")
    @patch("haso_payment.helpers.generate_hash")
    @patch("haso_payment.helpers.generate_salt")
    def test_get(self, mock_generate_salt, mock_generate_hash, mock_get):
        response = self._mock_response(
            status_code=200,
            content=self._get_response("orders_checkout_response"),
            headers={"Content-Type": "application/json"},
        )
        mock_get.return_value = response
        mock_generate_hash.return_value = "test-hash"
        mock_generate_salt.return_value = "test-salt"

        request = self.request_factory.get("/payment-gateway/haso/")
        request.GET = {"sessionId": "test-session-id"}
        response = self.view.as_view()(request)
        mock_generate_hash.assert_called_once_with(
            salt="test-salt", session_id="test-session-id",
            hash_key="your-extension-hash-key"
        )

        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertIsInstance(response, TemplateResponse)
        self.assertEqual(response.template_name, "haso_payment.html")

        context = response.context_data
        self.assertIn("payment_form_html", context)
