"""Shared SQLAlchemy model base and common helpers.

Every persistent model inherits from :class:`BaseModel`, which provides the
BIGINT auto-increment primary key required by the approved database design.
"""

from __future__ import annotations

from datetime import datetime, timezone

from app.extensions import db

# Surrogate-key column type shared by primary and foreign keys so the two always
# match. BIGINT on MySQL (the production target); INTEGER on SQLite, where
# auto-increment only applies to a column declared exactly as INTEGER PRIMARY KEY.
BigIntegerType = db.BigInteger().with_variant(db.Integer, "sqlite")


def utcnow() -> datetime:
    """Return the current UTC time as a naive ``datetime``.

    MySQL ``DATETIME`` columns are timezone-naive, so timestamps are stored in
    UTC without an attached timezone to keep comparisons consistent.
    """
    return datetime.now(timezone.utc).replace(tzinfo=None)


class BaseModel(db.Model):
    """Abstract base class for all models.

    Supplies the internal ``id`` BIGINT auto-increment primary key used by every
    table in the schema. Domain models add their own columns, public identifiers
    and timestamps via the mixins in :mod:`app.models.mixins`.
    """

    __abstract__ = True

    id = db.Column(BigIntegerType, primary_key=True, autoincrement=True)

    def __repr__(self) -> str:
        return f"<{self.__class__.__name__} id={self.id}>"
