from decimal import Decimal

from django.db import models
from django.utils import timezone

from shop_management.models.base import DataRoot
from shop_management.models.data.customer import Customer
from shop_management.models.data.product import Product
from shop_management.models.data.shop import Shop
from shop_management.models.data.utils import Currency, Unit


class Quotation(DataRoot):
    """Price quotation for visitors — does not affect stock or accounts."""
    shop = models.ForeignKey(Shop, on_delete=models.CASCADE, related_name="quotations")
    customer = models.ForeignKey(
        Customer,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="quotations",
    )
    quotation_date = models.DateField(default=timezone.now)
    currency = models.ForeignKey(
        Currency,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="quotations",
    )
    amount = models.DecimalField(
        max_digits=10, decimal_places=2, null=True, blank=True, default=0
    )
    notes = models.TextField(blank=True, null=True)
    visitor_name = models.CharField(max_length=255, blank=True, null=True)
    visitor_contact = models.CharField(max_length=50, blank=True, null=True)
    valid_until = models.DateField(null=True, blank=True)
    is_deleted = models.BooleanField(default=False)

    class Meta:
        ordering = ["-quotation_date", "-id"]

    def __str__(self):
        visitor = self.visitor_name or (
            self.customer.name if self.customer else "Visitor"
        )
        return f"Quotation #{self.id} for {visitor}"

    @property
    def total_amount(self):
        key = self.currency.title if self.currency else "Unknown Currency"
        total = sum(
            (item.quantity or 0) * (item.unit_price or Decimal("0"))
            for item in self.quotation_items.all()
        )
        return {key: total}

    @property
    def effective_total_amount(self):
        base = self.total_amount
        discount = self.amount or Decimal("0")
        return {currency: total - discount for currency, total in base.items()}


class QuotationItem(DataRoot):
    quotation = models.ForeignKey(
        Quotation, on_delete=models.CASCADE, related_name="quotation_items"
    )
    product = models.ForeignKey(
        Product,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="quotation_items",
    )
    quantity = models.PositiveIntegerField(default=1)
    unit = models.ForeignKey(Unit, on_delete=models.SET_NULL, null=True, blank=True)
    unit_price = models.DecimalField(max_digits=10, decimal_places=2)

    def __str__(self):
        name = self.product.name if self.product else "Item"
        return f"{self.quantity} x {name}"
