<?php

declare(strict_types=1);

namespace App\Models\Concerns;

use Illuminate\Database\Eloquent\Model;
use RuntimeException;

/**
 * Marks a model as an immutable historical record.
 *
 * The audit trail is only worth having if it cannot be quietly rewritten, so
 * updates and deletes are refused at the model layer rather than merely
 * discouraged by convention. Anything that needs correcting is corrected by
 * appending a new record.
 *
 * @phpstan-require-extends Model
 */
trait AppendOnly
{
    public static function bootAppendOnly(): void
    {
        static::updating(function ($model): void {
            throw new RuntimeException(sprintf(
                '[%s] records are append-only and cannot be updated.',
                class_basename($model)
            ));
        });

        static::deleting(function ($model): void {
            throw new RuntimeException(sprintf(
                '[%s] records are append-only and cannot be deleted.',
                class_basename($model)
            ));
        });
    }

    /** These tables carry only created_at; there is nothing to touch. */
    public function getUpdatedAtColumn(): ?string
    {
        return null;
    }
}
