<?php

namespace App\Modules\Pilkades\Observers;

use App\Modules\Pilkades\Models\Desa;
use App\Modules\Pilkades\Services\LandingPageCacheService;
use Illuminate\Database\Eloquent\Model;

/**
 * Generic observer for any tenant-scoped model that appears on the public
 * landing page (Banner, Countdown, Candidate, Faq, Contact, LandingPage
 * itself). Resolves the owning Desa via desa_id and busts its cache entry
 * so Admin Desa edits are reflected without waiting for the cache TTL.
 */
class InvalidatesLandingPageCache
{
    public function __construct(protected LandingPageCacheService $cache) {}

    public function saved(Model $model): void
    {
        $this->invalidate($model);
    }

    public function deleted(Model $model): void
    {
        $this->invalidate($model);
    }

    protected function invalidate(Model $model): void
    {
        $desaId = $model->desa_id ?? null;

        if (! $desaId) {
            return;
        }

        $desa = Desa::withoutGlobalScopes()->find($desaId);

        if ($desa) {
            $this->cache->forget($desa);
        }
    }
}
