<?php

namespace Tests\Feature;

use Illuminate\Support\Str;

use App\Models\Page;
use App\Models\Timetable;

trait ContentElementsSearchTestTrait
{
    abstract protected function getFactory();

    public function test_a_content_element_can_be_searched_for()
    {
        $page = Page::factory()->create();
        $content_element = $this->createContentElement($this->getFactory(), null, null, 'search');

        $page = $content_element->pages->first();
        $page->publish();
        $page->refresh();

        $fields = $content_element->content->search_fields;
        $this->assertNotNull($fields);
        //$this->assertTrue(count($fields) > 0);

        if (!$content_element->content instanceof Timetable) {
            foreach ($fields as $field) {
                if ($content_element->content->{$field}) {
                    $terms = collect(explode(' ', Str::replace('.', '', $content_element->content->{$field})))
                        ->sortByDesc(function ($term) {
                            return Str::length($term);
                        })
                        ->values()
                        ->first();

                    $this->assertNotNull($terms);

                    $preview = $content_element->content->getSearchResultPreview($terms);
                    $this->assertNotNull($preview);

                    cache()->tags(['search'])->flush();
                    $this->json('POST', route('search'), ['terms' => $terms, 'paginate_count' => 1000])
                         ->assertSuccessful()
                         ->assertJsonFragment([
                            'preview' => $preview,
                         ]);
                }
            }
        }
    }
}
