<?php

declare(strict_types=1);

namespace App\Observers;

use App\Models\GroupRelease;
use App\Services\Profile\CreatorJourneyService;

final class GroupReleaseObserver
{
    public function __construct(private readonly CreatorJourneyService $journeys)
    {
    }

    public function created(GroupRelease $release): void
    {
        $this->queueAffectedUsers($release);
    }

    public function updated(GroupRelease $release): void
    {
        if (! $release->wasChanged(['status', 'visibility', 'released_at', 'published_at', 'deleted_at', 'group_id'])) {
            return;
        }

        $this->queueAffectedUsers($release);
    }

    public function deleted(GroupRelease $release): void
    {
        $this->queueAffectedUsers($release);
    }

    public function restored(GroupRelease $release): void
    {
        $this->queueAffectedUsers($release);
    }

    public function forceDeleted(GroupRelease $release): void
    {
        $this->queueAffectedUsers($release);
    }

    private function queueAffectedUsers(GroupRelease $release): void
    {
        $userIds = $release->contributorLinks()
            ->pluck('user_id')
            ->filter()
            ->map(fn ($userId): int => (int) $userId)
            ->unique()
            ->values();

        foreach ($userIds as $userId) {
            $this->journeys->requestRebuild((int) $userId);
        }
    }
}