import uuid
from datetime import datetime
from decimal import Decimal
from enum import Enum

from sqlalchemy import (
    Boolean,
    DateTime,
    ForeignKey,
    Integer,
    Numeric,
    String,
    Uuid,
    func,
)
from sqlalchemy.orm import Mapped, mapped_column

from app.db.session import Base


class DiscountType(str, Enum):
    PERCENTAGE = "percentage"
    FIXED_AMOUNT = "fixed_amount"


class PromoCode(Base):
    """A discount code a customer can apply at checkout (see
    app.api.v1.endpoints.orders.checkout and
    app.services.promo.validate_promo_code). Scope narrows in two
    steps: merchant_id null means platform-wide (any merchant's
    branch); merchant_id set + branch_id null means every branch of
    that merchant; both set means just that one branch — created
    either by an admin (any of the three) or a merchant owner (their
    own merchant, optionally narrowed to one of their own branches,
    see app.api.v1.endpoints.promo_codes). branch_id is never set
    without merchant_id — a branch always implies its merchant, so
    there's no scope where only branch_id would be meaningful.

    discount_value's meaning depends on discount_type: a percentage
    (0-100) of the order subtotal, or a flat ETB amount off. Only
    percentage discounts use max_discount_amount, to cap an otherwise
    unbounded percentage-of-a-large-order discount — meaningless (and
    left null) for a fixed amount, which is already its own cap.

    usage_limit is the total redemptions across every customer;
    usage_limit_per_customer caps how many times any one customer can
    use it (e.g. "first order only" == 1). Both null means unlimited.
    times_used is a running counter, incremented on redemption (see
    app.services.promo.redeem_promo_code) — kept here rather than
    always COUNTing PromoCodeRedemption rows so checking the limit is
    a single indexed column read, not an aggregate query, on every
    checkout attempt.

    is_active is a manual kill switch, independent of valid_from/
    valid_until — lets a code be paused without deleting it or waiting
    for its natural expiry.
    """

    __tablename__ = "promo_codes"

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
    code: Mapped[str] = mapped_column(
        String(30), unique=True, index=True, nullable=False
    )
    merchant_id: Mapped[uuid.UUID | None] = mapped_column(
        Uuid, ForeignKey("merchants.id", ondelete="CASCADE"), nullable=True, index=True
    )
    branch_id: Mapped[uuid.UUID | None] = mapped_column(
        Uuid, ForeignKey("branches.id", ondelete="CASCADE"), nullable=True, index=True
    )
    created_by_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("users.id"), nullable=False
    )

    discount_type: Mapped[str] = mapped_column(String(20), nullable=False)
    discount_value: Mapped[Decimal] = mapped_column(Numeric(10, 2), nullable=False)
    max_discount_amount: Mapped[Decimal | None] = mapped_column(
        Numeric(10, 2), nullable=True
    )
    min_order_amount: Mapped[Decimal | None] = mapped_column(
        Numeric(10, 2), nullable=True
    )

    usage_limit: Mapped[int | None] = mapped_column(Integer, nullable=True)
    usage_limit_per_customer: Mapped[int | None] = mapped_column(Integer, nullable=True)
    times_used: Mapped[int] = mapped_column(Integer, nullable=False, default=0)

    valid_from: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    valid_until: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
    is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)

    created_at: Mapped[datetime] = mapped_column(
        DateTime, server_default=func.now(), nullable=False
    )
    updated_at: Mapped[datetime] = mapped_column(
        DateTime, server_default=func.now(), onupdate=func.now(), nullable=False
    )


class PromoCodeRedemption(Base):
    """One customer's use of a PromoCode on one order — unique on
    order_id (a single order can only carry one applied code, matching
    CheckoutRequest.promo_code being a single optional field, not a
    list). discount_amount is a snapshot of what was actually deducted
    on this order, immune to the code's own discount_value changing
    later, same reasoning as OrderItem's own snapshot fields."""

    __tablename__ = "promo_code_redemptions"

    id: Mapped[uuid.UUID] = mapped_column(Uuid, primary_key=True, default=uuid.uuid4)
    promo_code_id: Mapped[uuid.UUID] = mapped_column(
        Uuid,
        ForeignKey("promo_codes.id", ondelete="CASCADE"),
        nullable=False,
        index=True,
    )
    customer_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("users.id"), nullable=False, index=True
    )
    order_id: Mapped[uuid.UUID] = mapped_column(
        Uuid, ForeignKey("orders.id", ondelete="CASCADE"), unique=True, nullable=False
    )
    discount_amount: Mapped[Decimal] = mapped_column(Numeric(10, 2), nullable=False)

    created_at: Mapped[datetime] = mapped_column(
        DateTime, server_default=func.now(), nullable=False
    )
