"""
Schema migration model for tracking Alembic database migrations.

Tracks which database schema migrations have been applied, when, and by whom
for database version control and migration management.
"""

from datetime import datetime
from typing import Optional

from sqlalchemy import String, Text, TIMESTAMP
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.sql import func

from .base import Base


class SchemaMigration(Base):
    """
    Schema migration model for tracking Alembic database migrations.

    Records database schema version changes applied via Alembic migrations.
    Used to track which migrations have been applied, when they were applied,
    and the SQL executed for audit and rollback purposes.

    Note: This model does NOT use UUIDMixin as it uses version_id as the
    primary key to match Alembic's migration tracking system.

    Attributes:
        version_id: Alembic migration version identifier (primary key)
        description: Description of what the migration does
        applied_at: When the migration was applied
        applied_by: User or system that applied the migration
        migration_sql: SQL executed during the migration
    """

    __tablename__ = "schema_migrations"

    # Primary key - Alembic version identifier
    version_id: Mapped[str] = mapped_column(
        String(100),
        primary_key=True,
        doc="Alembic migration version identifier"
    )

    # Migration details
    description: Mapped[Optional[str]] = mapped_column(
        Text,
        doc="Description of what the migration does"
    )

    # Application tracking
    applied_at: Mapped[datetime] = mapped_column(
        TIMESTAMP,
        nullable=False,
        server_default=func.now(),
        doc="When the migration was applied"
    )

    applied_by: Mapped[Optional[str]] = mapped_column(
        String(255),
        doc="User or system that applied the migration"
    )

    # Migration SQL
    migration_sql: Mapped[Optional[str]] = mapped_column(
        Text,
        doc="SQL executed during the migration"
    )

    def __repr__(self) -> str:
        """String representation of the schema migration."""
        return f"<SchemaMigration(version='{self.version_id}', applied_at='{self.applied_at}')>"
