from datetime import datetime
from atomsql.orm import fields


class ImmutableLedgerMixin:
    """
    Mixin that enforces Write Once Read Many (WORM) semantics.
    Features:
      - Adds an 'ingested_at' timestamp automatically.
      - Prevents updates and deletions of records once created (raises PermissionError)
    """

    ingested_at = fields.DateTimeField(default=datetime.now)

    def save(self):
        """
        Overrides save to prevent updates.
        Only allows saving if the record has no ID (is new)
        """
        if getattr(self, "id", None) is not None:
            table = getattr(self, "_table_name", "unknown")
            raise PermissionError(
                f"Immutable Ledger Violation: Cannot update existing record in table '{table}'."
            )
        super().save()

    def delete(self):
        """
        Overrides delete to prevent deletions.
        Always raises PermissionError.
        """
        table = getattr(self, "_table_name", "unknown")
        raise PermissionError(
            f"Immutable Ledger Violation: Cannot delete record from table '{table}'."
        )
