"""Public storefront view tests."""

from django.contrib.auth.models import User
from django.test import TestCase, override_settings

from allianceauth.tests.auth_utils import AuthUtils

from shop.models import Shop

# Use plain (non-manifest) static storage so {% static 'shop/storefront.css' %} resolves
# in tests without a built manifest.
no_manifest_static = override_settings(STORAGES={
    "default": {"BACKEND": "django.core.files.storage.FileSystemStorage"},
    "staticfiles": {"BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage"},
})


def _user(username):
    u = AuthUtils.create_user(username)
    AuthUtils.add_main_character_2(u, username, 1_000_000 + u.pk, corp_id=2001, disconnect_signals=True)
    return User.objects.get(pk=u.pk)


@no_manifest_static
class StorefrontTests(TestCase):
    def setUp(self):
        self.owner = _user("owner")
        self.published = Shop.objects.create(slug="pub", name="Pub Shop", created_by=self.owner, is_published=True)
        self.draft = Shop.objects.create(slug="draft", name="Draft Shop", created_by=self.owner, is_published=False)

    def test_published_shop_renders_name_and_disclaimer(self):
        resp = self.client.get("/shop/pub/", SERVER_NAME="localhost")
        self.assertEqual(resp.status_code, 200)
        self.assertContains(resp, "Pub Shop")
        self.assertContains(resp, "CCP hf")

    def test_unpublished_shop_is_404_for_anonymous(self):
        resp = self.client.get("/shop/draft/", SERVER_NAME="localhost")
        self.assertEqual(resp.status_code, 404)

    def test_owner_can_preview_unpublished(self):
        self.client.force_login(self.owner)
        resp = self.client.get("/shop/draft/", SERVER_NAME="localhost")
        self.assertEqual(resp.status_code, 200)
        self.assertContains(resp, "only managers can see this preview")

    def test_unknown_slug_is_404(self):
        resp = self.client.get("/shop/nope/", SERVER_NAME="localhost")
        self.assertEqual(resp.status_code, 404)
