<?php

namespace App\Observers;

use App\Jobs\SyncAiProductIndexJob;
use App\Models\Item;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Schema;

class ItemCatalogObserver
{
    private const CACHE_KEY = 'meta_catalog_feed_xml';

    public function saved(Item $item): void
    {
        Cache::forget(self::CACHE_KEY);
        $this->queueAiIndexRefresh($item);
    }

    public function deleted(Item $item): void
    {
        Cache::forget(self::CACHE_KEY);
        $this->queueAiIndexRemoval($item);
    }

    protected function queueAiIndexRefresh(Item $item): void
    {
        if (!Schema::hasTable('ai_product_indices')) {
            return;
        }

        SyncAiProductIndexJob::dispatch((int) $item->id);
    }

    protected function queueAiIndexRemoval(Item $item): void
    {
        if (!Schema::hasTable('ai_product_indices')) {
            return;
        }

        SyncAiProductIndexJob::dispatch((int) $item->id, true);
    }
}
