<?php

    namespace App\Engines;

    use Illuminate\Support\Collection;
    use Laravel\Scout\Engines\AlgoliaEngine;

    class AdvancedAlgoliaEngine extends AlgoliaEngine
    {

        protected $index;

        public function update($models)
        {
            if ($models->isEmpty()) {
                return;
            }

            $index = $this->algolia->initIndex($models->first()->searchableAs());

            if ($this->usesSoftDelete($models->first()) && config('scout.soft_delete', false)) {
                $models->each->pushSoftDeleteMetadata();
            }

            $index->addObjects($models->map(function ($model) {
                $array = array_merge(
                    $model->toSearchableArray(), $model->scoutMetadata()
                );

                if (empty($array)) {
                    return;
                }

                try {
                    $index = $this->algolia->initIndex($model->searchableAs());
                    $algoliaObject = $index->getObject($model->getKey());
                    if ($this->needsUpdate($algoliaObject, $array)) {
                        return array_merge(['objectID' => $model->getScoutKey()], $array);
                    }
                } catch (\Exception $e) {
                    if ((int)$e->getCode() == 404) {
                        return array_merge(['objectID' => $model->getScoutKey()], $array);
                    }

                    return;
                }
            })->filter()->values()->all());
        }

        public function needsUpdate($algoliaObject, $localObject)
        {
            if(!isset($algoliaObject['updated_at'])) {
                return true;
            }

            return $algoliaObject['updated_at'] != $localObject['updated_at'] ? true : false;
        }

    }