from decimal import Decimal

from django.db import models


class Category(models.Model):
    name = models.CharField(max_length=120, unique=True)
    slug = models.SlugField(unique=True)
    description = models.TextField(blank=True)
    sort_order = models.PositiveIntegerField(default=0)

    class Meta:
        ordering = ["sort_order", "name"]

    def __str__(self):
        return self.name


class Product(models.Model):
    category = models.ForeignKey(Category, on_delete=models.PROTECT, related_name="products")
    name = models.CharField(max_length=160)
    slug = models.SlugField(unique=True)
    short_description = models.CharField(max_length=220)
    description = models.TextField()
    material = models.CharField(max_length=120, blank=True)
    price_from = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True)
    collection_note = models.CharField(max_length=180, blank=True)
    is_featured = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ["name"]

    def __str__(self):
        return self.name

    @property
    def price_label(self):
        if self.price_from is None:
            return "Preis auf Anfrage"
        quantized = self.price_from.quantize(Decimal("1.00"))
        return f"ab {quantized:,.2f} €".replace(",", "X").replace(".", ",").replace("X", ".")


class ContactInquiry(models.Model):
    class PreferredContactMethod(models.TextChoices):
        PHONE = "phone", "Telefon"
        EMAIL = "email", "E-Mail"

    class Status(models.TextChoices):
        NEW = "new", "Neu"
        CONTACTED = "contacted", "Kontaktiert"
        CLOSED = "closed", "Abgeschlossen"

    product = models.ForeignKey(
        Product,
        on_delete=models.SET_NULL,
        related_name="inquiries",
        blank=True,
        null=True,
    )
    name = models.CharField(max_length=120)
    email = models.EmailField()
    phone = models.CharField(max_length=40, blank=True)
    subject = models.CharField(max_length=160, blank=True)
    message = models.TextField()
    preferred_contact_method = models.CharField(
        max_length=10,
        choices=PreferredContactMethod.choices,
        default=PreferredContactMethod.PHONE,
    )
    status = models.CharField(max_length=20, choices=Status.choices, default=Status.NEW)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created_at"]

    def __str__(self):
        return f"{self.name} – {self.subject or 'Allgemeine Anfrage'}"
