<?php

declare(strict_types=1);

namespace App\Observers;

use App\Models\Document;
use App\Models\DocumentVersion;

class DocumentObserver
{
    /**
     * Handle the Document "updating" event.
     * Store the previous version before the content changes.
     */
    public function updating(Document $document): void
    {
        // Only create a version if content has changed
        if ($document->isDirty('content')) {
            // Store the previous version
            DocumentVersion::create([
                'document_id' => $document->id,
                'version' => $document->version,
                'content' => $document->getOriginal('content'),
                'created_by' => auth()->id(),
            ]);

            // Increment version number
            $document->version = $document->version + 1;
        }
    }
}
