"""Database models for NoticeCard."""

from datetime import datetime, timezone
from sqlalchemy import Column, Integer, String, DateTime, create_engine, event
from sqlalchemy.orm import DeclarativeBase, sessionmaker


class Base(DeclarativeBase):
    """Base class for all models."""
    pass


class Card(Base):
    """Card model for storing notice cards."""
    
    __tablename__ = "cards"
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    title = Column(String, nullable=False, index=True)
    description = Column(String, nullable=True)
    created_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), nullable=False)
    updated_at = Column(DateTime, default=lambda: datetime.now(timezone.utc), nullable=False)


@event.listens_for(Card, 'before_update')
def receive_before_update(mapper, connection, target):
    """Update the updated_at timestamp before update."""
    target.updated_at = datetime.now(timezone.utc)


def get_engine(db_path: str):
    """Create database engine."""
    return create_engine(f"sqlite:///{db_path}", connect_args={"check_same_thread": False})


def init_db(db_path: str):
    """Initialize database with tables."""
    engine = get_engine(db_path)
    Base.metadata.create_all(bind=engine)
    return engine


def get_session_maker(engine):
    """Create session maker."""
    return sessionmaker(autocommit=False, autoflush=False, bind=engine)
