<?php

namespace App\Observers;

use App\Models\ContentType;
use App\Models\ContentTypeSlugHistory;
use App\Services\ContentTypes\ContentTypeSlugResolver;

class ContentTypeObserver
{
    public function created(ContentType $contentType): void
    {
        app(ContentTypeSlugResolver::class)->flushCaches();
    }

    public function updated(ContentType $contentType): void
    {
        if ($contentType->wasChanged('slug')) {
            $oldSlug = strtolower(trim((string) $contentType->getOriginal('slug')));
            $newSlug = strtolower(trim((string) $contentType->slug));

            if ($oldSlug !== '' && $oldSlug !== $newSlug) {
                ContentTypeSlugHistory::query()->updateOrCreate(
                    ['old_slug' => $oldSlug],
                    ['content_type_id' => $contentType->id],
                );
            }
        }

        app(ContentTypeSlugResolver::class)->flushCaches();
    }

    public function deleted(ContentType $contentType): void
    {
        app(ContentTypeSlugResolver::class)->flushCaches();
    }
}
