"""Shared domain services."""

from __future__ import annotations

from dataclasses import dataclass, field

from .entities import Order, Product
from .policies import DefaultStockPolicy, DiscountPolicy, StockPolicy, TieredDiscountPolicy
from .value_objects import Money, Quantity


@dataclass
class PricingService:
    discount_policy: DiscountPolicy = field(default_factory=TieredDiscountPolicy)

    def calculate_subtotal(self, order: Order) -> Money:
        return order.total_before_discount()

    def calculate_discount(self, order: Order) -> Money:
        subtotal = self.calculate_subtotal(order)
        return self.discount_policy.calculate_discount(order.customer, subtotal)

    def calculate_final_total(self, order: Order) -> Money:
        subtotal = self.calculate_subtotal(order)
        discount = self.calculate_discount(order)
        return subtotal - discount


@dataclass
class InventoryService:
    stock_policy: StockPolicy = field(default_factory=DefaultStockPolicy)

    def reserve(self, product: Product, quantity: Quantity) -> None:
        self.stock_policy.ensure_reservable(product, quantity)
        product.reserve(quantity)

    def reserve_order(self, order: Order) -> None:
        for line in order.lines:
            self.reserve(line.product, line.quantity)
