from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase

from vbv_lernwelt.core.model_utils import add_countries, add_organisations
from vbv_lernwelt.core.models import Country, Organisation, User


class EntitiesViewTest(APITestCase):
    def setUp(self) -> None:
        self.user = User.objects.create_user(
            "testuser", "test@example.com", "testpassword"
        )
        self.client.login(username="testuser", password="testpassword")
        add_organisations()
        add_countries()

    def test_list_organisation_entities(self) -> None:
        # It seems that different locales handle ordering differently (especially with lower case letters)
        # As such we delete entries that start with lower case letters
        Organisation.objects.filter(organisation_id__in=[1, 2, 3]).delete()

        # GIVEN
        url = reverse("list_entities")

        self.user.language = "it"
        self.user.save()

        # WHEN
        response = self.client.get(url)

        # THEN
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        organisations = response.data["organisations"]

        self.assertEqual(
            organisations[-1],
            {
                "id": 28,
                "name": "Zurigo",
            },
        )

        countries = response.data["countries"]

        self.assertEqual(
            countries[0],
            {
                "id": 1,
                "name": "Afghanistan",
            },
        )

    def test_list_country_entities_ordered_by_country_id(self) -> None:
        # GIVEN
        url = reverse("list_entities")

        first_country = Country.objects.get(country_id=1)

        # WHEN
        response = self.client.get(url)

        # THEN
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        countries = response.data["countries"]

        self.assertEqual(
            countries[0],
            {
                "id": first_country.country_id,
                "name": first_country.name_de,
            },
        )

    def test_list_country_entities_ordered_by_order_id(self) -> None:
        # GIVEN
        url = reverse("list_entities")

        switzerland = Country.objects.get(name_de="Schweiz")
        switzerland.order_id = 1
        switzerland.save()

        # WHEN
        response = self.client.get(url)

        # THEN
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        countries = response.data["countries"]

        self.assertEqual(
            countries[0],
            {
                "id": switzerland.country_id,
                "name": switzerland.name_de,
            },
        )
