<?php

declare(strict_types=1);

namespace App\Observers;

use App\Models\Artwork;
use App\Models\ArtworkFeature;
use App\Services\HomepageService;
use App\Services\Profile\CreatorJourneyService;

final class ArtworkFeatureObserver
{
    public function __construct(
        private readonly HomepageService $homepage,
        private readonly CreatorJourneyService $journeys,
    )
    {
    }

    public function created(ArtworkFeature $feature): void
    {
        $this->homepage->clearFeaturedAndMedalCaches();
        $this->queueCreatorRebuild($feature);
    }

    public function updated(ArtworkFeature $feature): void
    {
        $this->homepage->clearFeaturedAndMedalCaches();
        $this->queueCreatorRebuild($feature);
    }

    public function deleted(ArtworkFeature $feature): void
    {
        $this->homepage->clearFeaturedAndMedalCaches();
        $this->queueCreatorRebuild($feature);
    }

    public function restored(ArtworkFeature $feature): void
    {
        $this->homepage->clearFeaturedAndMedalCaches();
        $this->queueCreatorRebuild($feature);
    }

    public function forceDeleted(ArtworkFeature $feature): void
    {
        $this->homepage->clearFeaturedAndMedalCaches();
        $this->queueCreatorRebuild($feature);
    }

    private function queueCreatorRebuild(ArtworkFeature $feature): void
    {
        $artwork = $feature->relationLoaded('artwork')
            ? $feature->artwork
            : Artwork::withTrashed()->find($feature->artwork_id);

        if (! $artwork) {
            return;
        }

        $this->journeys->requestRebuild((int) $artwork->user_id);
    }
}