"""
SCM Domain Entities — Price Management.

لیست قیمت‌ها و تخفیفات تأمین‌کنندگان.
"""
from dataclasses import dataclass, field
from datetime import date
from decimal import Decimal
from enum import Enum
from typing import Optional, List
from uuid import UUID

from shared.base_classes.entity import TenantEntity


class DiscountType(str, Enum):
    PERCENTAGE = "PERCENTAGE"
    FIXED_AMOUNT = "FIXED_AMOUNT"


@dataclass
class VendorPriceListItem(TenantEntity):
    """آیتم لیست قیمت."""
    price_list_id: Optional[UUID] = None
    item_id: Optional[UUID] = None
    item_code: str = ""
    item_name: str = ""
    uom_id: Optional[UUID] = None
    uom_code: str = ""
    unit_price: Decimal = Decimal("0")
    min_quantity: Decimal = Decimal("1")
    lead_time_days: int = 0
    notes: str = ""
    is_active: bool = True


@dataclass
class VendorPriceList(TenantEntity):
    """لیست قیمت تأمین‌کننده — Aggregate Root."""
    vendor_id: Optional[UUID] = None
    vendor_name: str = ""
    price_list_name: str = ""
    description: str = ""
    currency_code: str = "IRR"
    valid_from: Optional[date] = None
    valid_to: Optional[date] = None
    is_active: bool = True
    items: List[VendorPriceListItem] = field(default_factory=list)

    def is_valid(self) -> bool:
        """آیا لیست قیمت معتبر است؟"""
        today = date.today()
        if not self.is_active:
            return False
        if self.valid_from and today < self.valid_from:
            return False
        if self.valid_to and today > self.valid_to:
            return False
        return True

    def validate(self):
        if not self.vendor_id:
            raise ValueError("Vendor is required")
        if not self.price_list_name:
            raise ValueError("Price list name is required")


@dataclass
class PurchaseDiscount(TenantEntity):
    """تخفیف خرید."""
    vendor_id: Optional[UUID] = None
    item_id: Optional[UUID] = None
    item_group_id: Optional[UUID] = None
    discount_type: DiscountType = DiscountType.PERCENTAGE
    discount_value: Decimal = Decimal("0")
    min_quantity: Decimal = Decimal("0")
    min_amount: Decimal = Decimal("0")
    valid_from: Optional[date] = None
    valid_to: Optional[date] = None
    description: str = ""
    is_active: bool = True

    def is_valid(self) -> bool:
        today = date.today()
        if not self.is_active:
            return False
        if self.valid_from and today < self.valid_from:
            return False
        if self.valid_to and today > self.valid_to:
            return False
        return True

    def calculate_discount(self, quantity: Decimal, unit_price: Decimal) -> Decimal:
        """محاسبه مبلغ تخفیف."""
        if not self.is_valid():
            return Decimal("0")
        if quantity < self.min_quantity:
            return Decimal("0")
        total = quantity * unit_price
        if total < self.min_amount:
            return Decimal("0")
        if self.discount_type == DiscountType.PERCENTAGE:
            return total * self.discount_value / 100
        return self.discount_value
