"""Fitted-ship listing — one specific assembled ship on sale.

Unlike the other sections, a fitted listing is a single physical ship keyed by its
corptools ``item_id``; its fit is snapshotted into ``fit_json`` on recompute. Price is
manual (0 = Ask). Grouping by hull is a query-time concern, not a parent model.

``stock`` is 1 while the ship sits in the stockroom, 0 once it's gone. A gone listing
is deleted unless ``persist`` is set, in which case it stays as a build-to-order
advertisement keeping its last fit snapshot.
"""

from django.db import models

from .base import FeaturedListing
from .core import Shop


class FittedListing(FeaturedListing):
    """A single assembled, fitted ship listed for sale."""

    shop = models.ForeignKey(
        Shop, on_delete=models.CASCADE, related_name="fitted_listings"
    )
    eve_type = models.ForeignKey(
        "eveuniverse.EveType", on_delete=models.PROTECT, related_name="+"
    )  # the HULL type (grouping + title)
    item_id = models.BigIntegerField()  # the specific ship (join key to corptools)
    ship_name = models.CharField(max_length=255, blank=True, default="")  # buyer label
    price = models.PositiveBigIntegerField(default=0)  # ISK; 0 = "Ask" (manual only)
    stock = models.PositiveIntegerField(
        default=1
    )  # 1 = present; 0 = gone (build-to-order)
    miss_count = models.PositiveIntegerField(
        default=0
    )  # consecutive reconciles the ship was missing (grace before removal)
    persist = models.BooleanField(
        default=False
    )  # keep the listing when the ship is gone (build-to-order), else auto-remove
    description = models.TextField(blank=True, default="")
    fit_json = models.JSONField(default=dict, blank=True)  # reconstructed fit snapshot
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["shop", "item_id"], name="uniq_shop_fitted_item"
            )
        ]

    def __str__(self):
        return f"{self.shop.slug}: {self.eve_type.name} #{self.item_id}"

    @property
    def price_display(self) -> str:
        from ..formatting import format_isk

        return "Ask" if self.price == 0 else format_isk(self.price)

    @property
    def description_html(self) -> str:
        from ..markdown import render_markdown

        return render_markdown(self.description)
