import enum
from datetime import datetime
from typing import Optional, List, TYPE_CHECKING
from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, String, Text, UniqueConstraint
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.sql import func
from src.apps.base.models.base import Base

if TYPE_CHECKING:
    from src.apps.pricing_control.models.pricing_template_rate import PricingTemplateRate
    from src.apps.pricing_control.models.merchant_pricing_assignment import MerchantPricingAssignment


class PricingType(str, enum.Enum):
    INTERCHANGE_PLUS = "interchange_plus"
    TIERED = "tiered"
    FLAT_RATE = "flat_rate"
    CUSTOM = "custom"


class BillingCycle(str, enum.Enum):
    MONTHLY = "monthly"
    QUARTERLY = "quarterly"
    YEARLY = "yearly"


class PricingTemplate(Base):
    __tablename__ = "pricing_templates"

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    name: Mapped[str] = mapped_column(String(255), nullable=False)
    description: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
    pricing_type: Mapped[str] = mapped_column(String(30), nullable=False)
    billing_cycle: Mapped[str] = mapped_column(String(20), nullable=False)
    monthly_fee_cents: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
    setup_fee_cents: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
    is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
    # Self-referential FK for version chain (parent_template_id → previous version)
    parent_template_id: Mapped[Optional[int]] = mapped_column(
        Integer, ForeignKey("pricing_templates.id"), nullable=True
    )
    created_by_user_id: Mapped[Optional[int]] = mapped_column(
        Integer, ForeignKey("users.id"), nullable=True
    )
    created_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), server_default=func.now(), nullable=False
    )
    updated_at: Mapped[Optional[datetime]] = mapped_column(
        DateTime(timezone=True), nullable=True, onupdate=func.now()
    )
    deleted_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)

    # Self-referential relationship for version chain
    parent: Mapped[Optional["PricingTemplate"]] = relationship(
        "PricingTemplate",
        remote_side=[id],
        foreign_keys=[parent_template_id],
        back_populates="children",
    )
    children: Mapped[List["PricingTemplate"]] = relationship(
        "PricingTemplate",
        foreign_keys=[parent_template_id],
        back_populates="parent",
    )
    rates: Mapped[List["PricingTemplateRate"]] = relationship(
        "PricingTemplateRate",
        back_populates="template",
        cascade="all, delete-orphan",
        primaryjoin="and_(PricingTemplateRate.template_id == PricingTemplate.id, PricingTemplateRate.deleted_at == None)",
    )
    assignments: Mapped[List["MerchantPricingAssignment"]] = relationship(
        "MerchantPricingAssignment",
        back_populates="template",
    )
