from django.test import override_settings, TestCase
from django.urls import reverse

from power_query.defaults import create_defaults
from power_query.fixtures import (
    FormatterFactory,
    ParametrizerFactory,
    QueryFactory,
    ReportFactory,
    UserFactory,
)
from power_query.models import Formatter, Query, Report


@override_settings(POWER_QUERY_DB_ALIAS="default")
class TestPowerQuery(TestCase):
    databases = {"default"}

    @classmethod
    def setUpTestData(cls) -> None:
        cls.superuser = UserFactory(is_superuser=True, is_staff=True, is_active=True)

        # code should be unique but the test depends on both BAs having the same, empty code
        cls.user1 = UserFactory(is_superuser=False, is_staff=False, is_active=True)
        cls.user2 = UserFactory(is_superuser=False, is_staff=False, is_active=True)
        cls.user3 = UserFactory(is_superuser=False, is_staff=False, is_active=True)
        create_defaults()

        p = ParametrizerFactory()

        cls.query1: Query = QueryFactory(
            name="Query1", code="result=conn.all()", parametrizer=p
        )
        res = cls.query1.execute_matrix()
        assert res
        cls.formatter: Formatter = FormatterFactory(name="Queryset To HTML")
        cls.report1: Report = ReportFactory(formatter=cls.formatter, query=cls.query1)
        cls.report1.execute()

    def test_access_forbidden(self) -> None:
        url = reverse(
            "power_query:document",
            args=[self.report1.pk, self.report1.documents.first().pk],
        )
        self.client.login(username=self.user2.username, password="password")
        response = self.client.get(url)
        self.assertEqual(response.status_code, 403)
