"""Tenant bank details for contract payment instructions."""
from sqlalchemy import ForeignKey, String, Text, UniqueConstraint
from sqlalchemy.dialects.postgresql import UUID as PG_UUID
from sqlalchemy.orm import Mapped, mapped_column
from uuid import UUID

from src.database.base import TenantModel


class BankDetails(TenantModel):
    __tablename__ = "bank_details"

    __table_args__ = (
        UniqueConstraint("tenant_id", name="uq_bank_details_tenant"),
    )

    # Override tenant_id with explicit FK, mirroring Contract's override
    # pattern in models/contract.py. Uniqueness is enforced ONLY via the
    # __table_args__ constraint above (which creates its own unique index) —
    # no redundant index=True/unique=True on the column itself.
    tenant_id: Mapped[UUID] = mapped_column(
        PG_UUID(as_uuid=True),
        ForeignKey("accounts.id", ondelete="CASCADE"),
        nullable=False,
    )

    account_holder_name: Mapped[str] = mapped_column(String(255), nullable=False)
    bank_name: Mapped[str] = mapped_column(String(255), nullable=False)
    institution_number: Mapped[str] = mapped_column(String(3), nullable=False)
    transit_number: Mapped[str] = mapped_column(String(5), nullable=False)

    # Encrypted at rest (Fernet, src/core/encryption.py). Never store the
    # plaintext account number in any other column or log line.
    account_number_encrypted: Mapped[str] = mapped_column(Text, nullable=False)
    # Plaintext last 4 digits ONLY — lets GET responses / the PDF builder show
    # a masked value ("****1234") without a decrypt call on every read.
    account_number_last4: Mapped[str] = mapped_column(String(4), nullable=False)

    account_type: Mapped[str] = mapped_column(String(20), nullable=False)  # 'chequing' | 'savings'
    currency: Mapped[str] = mapped_column(String(3), nullable=False, server_default="CAD")
    branch_address: Mapped[str] = mapped_column(Text, nullable=False)
