<?php

namespace Tests\Tenant;

use Mtc\ContentManager\Models\ContentElement;
use Tests\TenantTestCase;
use Tests\UserForTenant;

class SearchControllerTest extends TenantTestCase
{
    use UserForTenant;


    public function testSearchRequiresTerm()
    {
        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->postJson(route('tenant.search'), []);

        $response->assertStatus(422);
    }

    public function testContentElementSearch()
    {
        ContentElement::factory()->create(['title' => 'foo', 'is_enabled' => true, 'drag_and_drop' => true]);
        ContentElement::factory()->create(['title' => 'foo baz bar', 'is_enabled' => true, 'drag_and_drop' => true]);
        ContentElement::factory()->create(['title' => 'lorem ipsum', 'is_enabled' => true, 'drag_and_drop' => true]);
        ContentElement::factory()->create([
            'title' => 'lorem ipsum',
            'subtitle' => 'foo baz',
            'is_enabled' => true,
            'drag_and_drop' => true
        ]);

        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->postJson(route('tenant.search.content'), [
                'term' => 'foo',
                'drag_and_drop' => false,
            ]);

        $response->assertStatus(200);
        $this->assertIsArray($response->json());
        $this->assertEquals(3, collect($response->json())->flatMap(fn ($entry) => $entry['items'])->count());
    }

    public function testOnlyPublishedContentElementSearch()
    {
        ContentElement::factory()->create(['title' => 'foo', 'is_enabled' => true, 'drag_and_drop' => true]);
        ContentElement::factory()->create(['title' => 'foo baz bar', 'is_enabled' => false]);
        ContentElement::factory()->create(['title' => 'lorem ipsum', 'is_enabled' => true, 'drag_and_drop' => true]);
        ContentElement::factory()->create([
            'title' => 'lorem ipsum',
            'is_enabled' => false,
            'subtitle' => 'foo baz',
        ]);

        $response = $this->actingAs($this->getUser())
            ->withHeader('X-Tenant', tenant('id'))
            ->postJson(route('tenant.search.content'), [
                'term' => 'foo',
                'drag_and_drop' => false,
            ]);

        $response->assertStatus(200);
        $this->assertIsArray($response->json());
        $this->assertEquals(1, collect($response->json())->flatMap(fn ($entry) => $entry['items'])->count());
    }
}
