"""QR Code model for tenant-scoped QR code registry."""
from __future__ import annotations

from datetime import datetime
from typing import Optional
from uuid import UUID

from sqlalchemy import Boolean, DateTime, Index, String, Text, UniqueConstraint
from sqlalchemy.dialects.postgresql import UUID as PG_UUID
from sqlalchemy.orm import Mapped, mapped_column

from src.database.base import TenantModel


class QRCode(TenantModel):
    """Tenant-scoped QR code entry for entrances, sections, plots, and contracts."""

    __tablename__ = "qr_codes"

    # Override tenant_id with explicit FK
    tenant_id: Mapped[UUID] = mapped_column(
        PG_UUID(as_uuid=True),
        nullable=False,
        index=False,  # rely on named index in __table_args__ instead
    )

    # -- Core fields -----------------------------------------------------------

    qr_type: Mapped[str] = mapped_column(
        String(50),
        nullable=False,
        comment="One of: entrance | section | plot | contract",
    )
    reference_id: Mapped[str] = mapped_column(
        String(255),
        nullable=False,
        comment="Section code, plot_ref, contract_number, or 'main' for entrance",
    )
    display_label: Mapped[Optional[str]] = mapped_column(String(255), nullable=True)
    content_url: Mapped[str] = mapped_column(Text(), nullable=False)

    # -- Storage keys ----------------------------------------------------------

    svg_s3_key: Mapped[Optional[str]] = mapped_column(Text(), nullable=True)
    pdf_s3_key: Mapped[Optional[str]] = mapped_column(Text(), nullable=True)

    # -- Status ----------------------------------------------------------------

    is_active: Mapped[bool] = mapped_column(Boolean(), nullable=False, default=True)
    generated_at: Mapped[Optional[datetime]] = mapped_column(
        DateTime(timezone=True), nullable=True
    )

    # -- Constraints & indexes -------------------------------------------------

    __table_args__ = (
        UniqueConstraint(
            "tenant_id",
            "qr_type",
            "reference_id",
            name="uq_qr_codes_tenant_type_ref",
        ),
        Index("ix_qr_codes_tenant", "tenant_id"),
    )
