import uuid
from datetime import datetime
from decimal import Decimal
from typing import Literal

from pydantic import BaseModel, ConfigDict, field_validator, model_validator


class PromoCodeCreateRequest(BaseModel):
    """Scope narrows in two steps: merchant_id null means platform-wide
    (any merchant's branch can redeem it) — only an admin may create a
    platform-wide code; a supplier must always set their own
    merchant_id, enforced in
    app.api.v1.endpoints.promo_codes.create_promo_code, not here.
    branch_id further narrows to just one of that merchant's branches
    — leave it unset for "every branch of this merchant." branch_id
    can't be set without merchant_id, and must actually belong to that
    merchant (also enforced in the endpoint, where the DB is
    available).

    max_discount_amount only makes sense for a percentage discount
    (caps an otherwise unbounded percentage-of-a-large-order amount) —
    rejected for a fixed_amount code, which is already its own cap."""

    code: str
    merchant_id: uuid.UUID | None = None
    branch_id: uuid.UUID | None = None
    discount_type: Literal["percentage", "fixed_amount"]
    discount_value: Decimal
    max_discount_amount: Decimal | None = None
    min_order_amount: Decimal | None = None
    usage_limit: int | None = None
    usage_limit_per_customer: int | None = None
    valid_from: datetime | None = None
    valid_until: datetime | None = None

    @field_validator("code")
    @classmethod
    def _clean_code(cls, v: str) -> str:
        v = v.strip().upper()
        if not v:
            raise ValueError("Code is required.")
        if not v.isalnum():
            raise ValueError("Code must be letters and numbers only.")
        return v

    @field_validator("discount_value")
    @classmethod
    def _positive_value(cls, v: Decimal) -> Decimal:
        if v <= 0:
            raise ValueError("discount_value must be greater than zero.")
        return v

    @field_validator("max_discount_amount", "min_order_amount")
    @classmethod
    def _non_negative(cls, v: Decimal | None) -> Decimal | None:
        if v is not None and v <= 0:
            raise ValueError("Must be greater than zero if provided.")
        return v

    @field_validator("usage_limit", "usage_limit_per_customer")
    @classmethod
    def _positive_limit(cls, v: int | None) -> int | None:
        if v is not None and v <= 0:
            raise ValueError("Must be greater than zero if provided.")
        return v

    @model_validator(mode="after")
    def _validate_combination(self) -> "PromoCodeCreateRequest":
        if self.discount_type == "percentage" and self.discount_value > 100:
            raise ValueError("A percentage discount can't exceed 100.")
        if (
            self.discount_type == "fixed_amount"
            and self.max_discount_amount is not None
        ):
            raise ValueError(
                "max_discount_amount only applies to a percentage discount."
            )
        if (
            self.valid_from is not None
            and self.valid_until is not None
            and self.valid_until <= self.valid_from
        ):
            raise ValueError("valid_until must be after valid_from.")
        if self.branch_id is not None and self.merchant_id is None:
            raise ValueError("branch_id requires merchant_id.")
        return self


class PromoCodeUpdateRequest(BaseModel):
    """Partial — only fields actually sent are changed. Deliberately
    doesn't allow changing code/discount_type/discount_value/
    merchant_id after creation (a code already advertised or redeemed
    shouldn't quietly change what it does) — deactivate it and create
    a new one instead."""

    is_active: bool | None = None
    max_discount_amount: Decimal | None = None
    min_order_amount: Decimal | None = None
    usage_limit: int | None = None
    usage_limit_per_customer: int | None = None
    valid_from: datetime | None = None
    valid_until: datetime | None = None


class PromoCodeOut(BaseModel):
    model_config = ConfigDict(from_attributes=True)

    id: uuid.UUID
    code: str
    merchant_id: uuid.UUID | None
    branch_id: uuid.UUID | None
    discount_type: str
    discount_value: Decimal
    max_discount_amount: Decimal | None
    min_order_amount: Decimal | None
    usage_limit: int | None
    usage_limit_per_customer: int | None
    times_used: int
    valid_from: datetime | None
    valid_until: datetime | None
    is_active: bool
    created_at: datetime
