"""ImportBatch — one scan run, aggregating many ImportTasks."""

from datetime import datetime

from sqlalchemy import DateTime, Integer, String, Text, func
from sqlalchemy.orm import Mapped, mapped_column, relationship

from .base import Base


class ImportBatch(Base):
    __tablename__ = "import_batch"

    id: Mapped[int] = mapped_column(Integer, primary_key=True)
    triggered_by: Mapped[str] = mapped_column(String(32), nullable=False)
    source_path: Mapped[str] = mapped_column(Text, nullable=False)
    scan_mode: Mapped[str] = mapped_column(String(16), nullable=False)  # quick|deep

    started_at: Mapped[datetime] = mapped_column(
        DateTime(timezone=True), nullable=False, server_default=func.now()
    )
    finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)

    total_files: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
    imported: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
    skipped: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
    failed: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
    attachments: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
    # Deep-scan only: count of already-imported files whose sidecar metadata
    # got re-applied this run (post/source/provenance upsert). Stays 0 on
    # quick-scan batches. See `Importer.import_one(deep_scan=True)`.
    refreshed: Mapped[int] = mapped_column(Integer, nullable=False, default=0)

    status: Mapped[str] = mapped_column(String(16), nullable=False, default="running", index=True)
    # running | complete | cancelled

    tasks = relationship("ImportTask", back_populates="batch", cascade="all, delete-orphan")
