from datetime import datetime
from typing import Optional, TYPE_CHECKING
from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, String, Text
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.merchants.models.merchant import Merchant


class MerchantBillingMethod(Base):
    __tablename__ = "merchant_billing_methods"

    id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
    merchant_id: Mapped[int] = mapped_column(
        Integer, ForeignKey("merchants.id"), nullable=False, unique=True, index=True
    )
    # TSEP token stored as plaintext — caller is responsible for not logging it
    tsep_token: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
    card_type: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
    masked_card: Mapped[Optional[str]] = mapped_column(String(20), nullable=True)
    billing_name: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
    is_active: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
    requires_revalidation: Mapped[bool] = mapped_column(
        Boolean, nullable=False, default=False, server_default="false"
    )
    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)

    merchant: Mapped["Merchant"] = relationship("Merchant")
