from __future__ import annotations

from datetime import datetime

from sqlalchemy import event
from sqlalchemy.orm import DeclarativeBase


class Base(DeclarativeBase):
    pass


@event.listens_for(Base, "before_insert", propagate=True)
def set_audit_fields_before_insert(mapper, connection, target) -> None:
    _ = mapper, connection
    now = datetime.now()
    if hasattr(target, "created_at") and getattr(target, "created_at", None) is None:
        setattr(target, "created_at", now)
    if hasattr(target, "updated_at") and getattr(target, "updated_at", None) is None:
        setattr(target, "updated_at", now)


@event.listens_for(Base, "before_update", propagate=True)
def set_audit_fields_before_update(mapper, connection, target) -> None:
    _ = mapper, connection
    if hasattr(target, "updated_at"):
        setattr(target, "updated_at", datetime.now())
