<?php

declare(strict_types=1);

namespace App\Observers;

use App\Jobs\RecalculateArtworkMedalStatsJob;
use App\Models\ArtworkAward;
use App\Services\UserStatsService;
use Illuminate\Support\Facades\DB;

class ArtworkAwardObserver
{
    public function __construct(
        private readonly UserStatsService $userStats,
    ) {}

    public function created(ArtworkAward $award): void
    {
        $this->refresh($award);
        $this->trackCreatorStats($award, +1);
    }

    public function updated(ArtworkAward $award): void
    {
        $this->refresh($award);
        // Medal changed – count stays the same; no stat change needed.
    }

    public function deleted(ArtworkAward $award): void
    {
        $this->refresh($award);
        $this->trackCreatorStats($award, -1);
    }

    private function refresh(ArtworkAward $award): void
    {
        RecalculateArtworkMedalStatsJob::dispatchSync((int) $award->artwork_id);
    }

    private function trackCreatorStats(ArtworkAward $award, int $delta): void
    {
        $creatorId = DB::table('artworks')
            ->where('id', $award->artwork_id)
            ->value('user_id');

        if (! $creatorId) {
            return;
        }

        if ($delta > 0) {
            $this->userStats->incrementAwardsReceived((int) $creatorId);
        } else {
            $this->userStats->decrementAwardsReceived((int) $creatorId);
        }
    }
}
