"""Storefront BPC section tests."""

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

from shop.models import BpcListing, BpcVariant, Shop
from shop.tests.test_stock import make_owner_character, make_ship_type
from shop.tests.test_views_backoffice import no_manifest_static


@no_manifest_static
class BpcSectionPageTests(TestCase):
    def setUp(self):
        self.user, self.char = make_owner_character()
        self.shop = Shop.objects.create(
            slug="pub",
            name="Pub",
            created_by=self.user,
            is_published=True,
            enabled_sections=["bpc"],
        )
        self.bp = make_ship_type(type_id=12040, name="Rifter Blueprint")
        listing = BpcListing.objects.create(shop=self.shop, eve_type=self.bp)
        BpcVariant.objects.create(
            listing=listing,
            me=10,
            te=20,
            runs=50,
            stock=2,
            price=8_000_000,
            price_per_run=160_000,
        )
        self.listing = listing

    def _detail_url(self):
        return reverse("storefront:bpc_item", args=[self.shop.slug, self.listing.pk])

    def test_section_renders_type_card(self):
        resp = self.client.get("/shop/pub/bpc/", SERVER_NAME="localhost")
        self.assertEqual(resp.status_code, 200)
        self.assertContains(resp, "Rifter Blueprint")
        # "From" is now the cheapest per-run price.
        self.assertContains(resp, "from 160K ISK/run")
        self.assertContains(resp, "/bpc/{}/".format(self.listing.pk))

    def test_table_view_is_sortable_and_paginated(self):
        resp = self.client.get("/shop/pub/bpc/?view=table", SERVER_NAME="localhost")
        self.assertEqual(resp.status_code, 200)
        self.assertContains(resp, "data-table")
        self.assertContains(resp, 'data-table-style="tailwind"')
        self.assertContains(resp, 'data-table-hidden-class="hidden"')
        self.assertContains(resp, "data-table-pager")
        self.assertContains(resp, 'data-sort="text"')  # Name
        self.assertContains(resp, 'data-sort="num"')  # Variants / Stock
        self.assertContains(resp, "data-sort-value=")

    def test_table_view_has_no_default_sort_arrow(self):
        resp = self.client.get("/shop/pub/bpc/?view=table", SERVER_NAME="localhost")
        self.assertNotContains(resp, "data-sort-default")

    def test_table_view_search_owned_by_controller(self):
        resp = self.client.get("/shop/pub/bpc/?view=table", SERVER_NAME="localhost")
        # Target the input element itself — the base filter's inline script always
        # mentions [data-search-input] by name, so match on the attribute in context.
        self.assertContains(resp, 'autocomplete="off" data-table-search')
        self.assertNotContains(resp, 'autocomplete="off" data-search-input')

    def test_grid_view_search_owned_by_base_filter(self):
        resp = self.client.get("/shop/pub/bpc/", SERVER_NAME="localhost")
        self.assertContains(resp, 'autocomplete="off" data-search-input')
        self.assertNotContains(resp, 'autocomplete="off" data-table-search')

    def test_detail_renders_variants(self):
        resp = self.client.get(self._detail_url(), SERVER_NAME="localhost")
        self.assertEqual(resp.status_code, 200)
        self.assertContains(resp, "Rifter Blueprint")
        # ME and TE are separate columns now.
        self.assertContains(resp, ">10<")
        self.assertContains(resp, ">20<")
        self.assertContains(resp, "50")
        self.assertContains(resp, "8M")  # price column
        self.assertContains(resp, "160K")  # price / run column

    def test_detail_unpublished_404_anon(self):
        self.shop.is_published = False
        self.shop.save(update_fields=["is_published"])
        resp = self.client.get(self._detail_url(), SERVER_NAME="localhost")
        self.assertEqual(resp.status_code, 404)

    def test_detail_wrong_shop_404(self):
        other = Shop.objects.create(
            slug="other", name="O", created_by=self.user, is_published=True
        )
        resp = self.client.get(
            reverse("storefront:bpc_item", args=[other.slug, self.listing.pk]),
            SERVER_NAME="localhost",
        )
        self.assertEqual(resp.status_code, 404)

    def test_featured_listing_sorts_first_and_is_starred(self):
        # A second, alphabetically-earlier listing that is NOT featured.
        atron = make_ship_type(type_id=608, name="Atron Blueprint")
        plain = BpcListing.objects.create(shop=self.shop, eve_type=atron)
        BpcVariant.objects.create(listing=plain, me=0, te=0, runs=10, stock=1, price=0)
        self.listing.featured = True
        self.listing.save(update_fields=["featured"])
        resp = self.client.get("/shop/pub/bpc/", SERVER_NAME="localhost")
        body = resp.content.decode()
        # Featured (Rifter) renders before the non-featured (Atron)...
        self.assertLess(body.index("Rifter Blueprint"), body.index("Atron Blueprint"))
        # ...and carries the star marker.
        self.assertContains(resp, "ti-star-filled")

    def test_hidden_variant_excluded_from_detail(self):
        BpcVariant.objects.create(
            listing=self.listing, me=2, te=4, runs=99, stock=5, price=1_000, hidden=True
        )
        resp = self.client.get(self._detail_url(), SERVER_NAME="localhost")
        self.assertNotContains(resp, "99")  # hidden variant's runs
        self.assertContains(resp, "50")  # visible variant remains

    def test_all_hidden_listing_dropped_from_section(self):
        self.listing.variants.update(hidden=True)
        resp = self.client.get("/shop/pub/bpc/", SERVER_NAME="localhost")
        self.assertNotContains(resp, "Rifter Blueprint")
        self.assertContains(resp, "No blueprint copies listed yet.")
