<?php

namespace Daylight\Core\Models\Concerns;

use Illuminate\Database\Eloquent\Model;

/**
 * Trait to ensure the search index stays in sync when related models change.
 *
 * This trait overrides the relationship methods to automatically trigger
 * search indexing when pivot tables are modified.
 */
trait SyncsSearchIndex
{
    /**
     * Boot the trait and register model events.
     */
    public static function bootSyncsSearchIndex(): void
    {
        // When the model is updated (including via $touches), re-index
        static::saved(function (Model $model) {
            if (method_exists($model, 'searchable')) {
                $model->searchable();
            }
        });

        static::deleted(function (Model $model) {
            if (method_exists($model, 'unsearchable')) {
                $model->unsearchable();
            }
        });

        if (method_exists(static::class, 'restored')) {
            static::restored(function (Model $model) {
                if (method_exists($model, 'searchable')) {
                    $model->searchable();
                }
            });
        }
    }

    /**
     * Sync categories and update search index.
     */
    public function syncCategories(array $ids): void
    {
        $this->categories()->sync($ids);
        $this->searchable();
    }

    /**
     * Attach categories and update search index.
     */
    public function attachCategories(array $ids): void
    {
        $this->categories()->attach($ids);
        $this->searchable();
    }

    /**
     * Detach categories and update search index.
     */
    public function detachCategories(?array $ids = null): void
    {
        $this->categories()->detach($ids);
        $this->searchable();
    }

    /**
     * Sync attribute values and update search index.
     */
    public function syncAttributeValues(array $ids): void
    {
        $this->attributeValues()->sync($ids);
        $this->searchable();
    }

    /**
     * Attach attribute values and update search index.
     */
    public function attachAttributeValues(array $ids): void
    {
        $this->attributeValues()->attach($ids);
        $this->searchable();
    }

    /**
     * Detach attribute values and update search index.
     */
    public function detachAttributeValues(?array $ids = null): void
    {
        $this->attributeValues()->detach($ids);
        $this->searchable();
    }

    /**
     * Sync labels and update search index.
     */
    public function syncLabels(array $ids): void
    {
        $this->labels()->sync($ids);
        $this->searchable();
    }

    /**
     * Force re-index this model in the search engine.
     */
    public function reindex(): void
    {
        if (method_exists($this, 'searchable')) {
            $this->searchable();
        }
    }
}
