# Disables for testing:
# pylint: disable=missing-docstring

from django.db import connection
from django_test_migrations.contrib.unittest_case import MigratorTestCase


class RemoveRegisteredServiceMigrationTestCase(MigratorTestCase):
    """This class is used to test the migration that removes Registered Services in favour of Service Revisions."""

    migrate_from = ("django_twined", "0006_service_revisions_and_events")
    migrate_to = ("django_twined", "0009_remove_registered_services")

    def prepare(self):
        """Prepare original data at migration 0006
        Note that these need to be done with custom SQL entries,
        because models may no longer exist as the repo evolves.

        These statements were generated by migrating the test server to 0006, opening the shell and manually creating the entries.
        Then, doing:
        ```py
            from django.db import connection
            print(connection.queries)
        ```
        shows the sql you executed within the shell context, which gets replicated here
        """

        with connection.cursor() as cursor:
            # Two statements for one registeredservice because it wan't correctly abstracted.
            cursor.execute(
                'INSERT INTO "django_twined_abstractregisteredservice" ("id", "name") VALUES (\'8e566475-0efb-46cd-8785-85516ce732f1\'::uuid, \'test-name\')'
            )
            cursor.execute(
                'INSERT INTO "django_twined_registeredservice" ("abstractregisteredservice_ptr_id") VALUES (\'8e566475-0efb-46cd-8785-85516ce732f1\'::uuid)'
            )
            cursor.execute(
                'INSERT INTO "django_twined_question" ("id", "asked", "answered", "service_revision_id", "registered_service_id") VALUES (\'e46d333e-0546-4702-9766-996d5c7beba1\'::uuid, NULL, NULL, NULL, \'8e566475-0efb-46cd-8785-85516ce732f1\'::uuid)',
            )

    def test_registered_service_migration(self):
        """Run the test itself."""

        # Ensure a service revision was created
        ServiceRevision = self.new_state.apps.get_model("django_twined", "ServiceRevision")
        self.assertEqual(ServiceRevision.objects.count(), 1)
        self.assertEqual(ServiceRevision.objects.filter(topic_id="8e566475-0efb-46cd-8785-85516ce732f1").count(), 1)

        # Ensure the new Service Revision has the correct topic_id and name
        sr = ServiceRevision.objects.first()
        self.assertEqual(str(sr.topic_id), "8e566475-0efb-46cd-8785-85516ce732f1")
        self.assertEqual(sr.name, "test-name")

        # Ensure the settings defaults were used to create unknown properties
        self.assertEqual(sr.namespace, "test-default-namespace")
        self.assertEqual(sr.project_name, "test-default-project-name")
        self.assertEqual(sr.tag, "test-default-tag")
