"""ImportBatch document model for tracking spreadsheet imports."""

from datetime import datetime, timezone
from enum import Enum
from typing import Any, Optional

from pydantic import Field

from winebox.db import MongoDocument, PyObjectId


class ImportStatus(str, Enum):
    """Status of an import batch."""

    UPLOADED = "uploaded"
    MAPPED = "mapped"
    PROCESSING = "processing"
    COMPLETED = "completed"
    FAILED = "failed"
    ROLLED_BACK = "rolled_back"


class ImportBatch(MongoDocument):
    """Tracks a spreadsheet import batch through the upload/map/process workflow."""

    owner_id: PyObjectId
    filename: str
    file_type: str  # "csv" or "xlsx"
    imported_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
    status: ImportStatus = ImportStatus.UPLOADED

    # Column mapping: header name -> wine field / "custom:FieldName" / "skip"
    column_mapping: Optional[dict[str, str]] = None

    # File checksum for duplicate detection (SHA-256 hex digest)
    file_checksum: Optional[str] = None

    # Headers that were not mapped to canonical wine fields
    unmapped_headers: list[str] = Field(default_factory=list)

    # Raw data from spreadsheet
    headers: list[str] = Field(default_factory=list)
    rows: list[dict[str, Any]] = Field(default_factory=list)
    row_count: int = 0
    preview_rows: list[dict[str, Any]] = Field(default_factory=list)

    # Processing results
    wines_created: int = 0
    rows_skipped: int = 0
    skipped_rows_detail: list[dict[str, Any]] = Field(default_factory=list)
    errors: list[str] = Field(default_factory=list)

    class Settings:
        name = "import_batches"
