"""
PRD-HWONB-012 §2.2 — merchant_onboarding_documents

doc_type is the 15-code enum GP actually accepts (confirmed verbatim via CERT,
PRD-001 §13.1 C-20): SMA, FS, BL, SS, PB, BR, PS, MM, FD, Tax, NP, ACH, PC, CH,
VITL, OTHER. Note `Tax` is Title-case, not `TAX` — GP rejects the all-caps form.
Stored as a String, not a DB enum, per the same state-machine-in-code convention
used for the application's status/current_step columns.
"""
from typing import Optional, TYPE_CHECKING
from sqlalchemy import String, Integer, DateTime, JSON, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.sql import func
from src.apps.base.models.base import Base
from datetime import datetime

if TYPE_CHECKING:
    from src.apps.merchant_onboarding.models.application import MerchantOnboardingApplication


class MerchantOnboardingDocument(Base):
    __tablename__ = "merchant_onboarding_documents"

    id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True, autoincrement=True)
    application_id: Mapped[int] = mapped_column(
        Integer, ForeignKey("merchant_onboarding_applications.id"), nullable=False, index=True
    )

    # SMA|FS|BL|SS|PB|BR|PS|MM|FD|Tax|NP|ACH|PC|CH|VITL|OTHER (PRD-HWONB-012 §2.2, CERT C-20)
    doc_type: Mapped[str] = mapped_column(String(10), nullable=False)

    file_name: Mapped[str] = mapped_column(String(255), nullable=False)
    content_type: Mapped[str] = mapped_column(String(100), nullable=False)
    size_bytes: Mapped[int] = mapped_column(Integer, nullable=False)  # validated <=2MB (prod limit) before upload
    s3_key: Mapped[str] = mapped_column(String(500), nullable=False)

    # GP's attachment id (int, 1-based, "attachmentId" per CERT C-22) — stored as string for
    # consistency with the other tsys_*_ref columns across this module.
    tsys_upload_ref: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
    tsys_synced_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
    tsys_errors: Mapped[Optional[dict]] = mapped_column(JSON, 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)

    application: Mapped["MerchantOnboardingApplication"] = relationship(
        "MerchantOnboardingApplication", back_populates="documents"
    )
