<?php

namespace Daylight\Core\Observers;

use Daylight\Core\Jobs\ReindexProductsJob;
use Daylight\Core\Models\AttributeValue;
use Daylight\Core\Models\Brand;
use Daylight\Core\Models\Category;
use Illuminate\Support\Facades\Bus;

/**
 * Observer that triggers product re-indexing when related models change.
 *
 * This observer should be registered for Brand, Category, and AttributeValue models
 * to ensure the search index stays in sync when these models are updated.
 */
class ProductSearchObserver
{
    /**
     * Handle the "saved" event for Brand.
     */
    public function savedBrand(Brand $brand): void
    {
        $this->queueProductReindex(
            $brand->products()->pluck('id')->toArray()
        );
    }

    /**
     * Handle the "saved" event for Category.
     */
    public function savedCategory(Category $category): void
    {
        $this->queueProductReindex(
            $category->products()->pluck('products.id')->toArray()
        );
    }

    /**
     * Handle the "saved" event for AttributeValue.
     */
    public function savedAttributeValue(AttributeValue $attributeValue): void
    {
        $this->queueProductReindex(
            $attributeValue->product()->pluck('products.id')->toArray()
        );
    }

    /**
     * Queue a job to re-index the given product IDs.
     */
    protected function queueProductReindex(array $productIds): void
    {
        if (empty($productIds)) {
            return;
        }

        // Dispatch job to queue to avoid blocking the request
        Bus::dispatch(new ReindexProductsJob($productIds));
    }
}
