<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\WithFaker;
use Tests\TestCase;

use App\Models\User;
use App\Models\Page;

class SessionTest extends TestCase
{
    public function test_the_session_remembers_the_page_tree_expanded_ids()
    {
        $page = Page::factory()->create();
        $sub_page = Page::factory()->create();

        $user = User::factory()->create();

        $this->json('POST', route('pages.expand'), ['ids' => $page->id])
            ->assertStatus(401);

        $this->signIn($user);

        $this->json('POST', route('pages.expand'), ['ids' => $page->id])
            ->assertStatus(403);

        $user->addRole('pages-editor');
        $user->refresh();

        $this->json('POST', route('pages.expand'), ['ids' => $page->id])
            ->assertSuccessful()
            ->assertSessionHas('expanded_page_ids');

        $this->assertTrue(session()->has('expanded_page_ids'));

        $this->assertTrue(collect(session()->get('expanded_page_ids'))->contains($page->id));

        $this->json('POST', route('pages.expand'), ['ids' => [$sub_page->id]])
            ->assertSuccessful();

        $this->assertTrue(collect(session()->get('expanded_page_ids'))->contains($page->id));
        $this->assertTrue(collect(session()->get('expanded_page_ids'))->contains($sub_page->id));

        // add toggle it off
        $this->json('POST', route('pages.expand'), ['ids' => $page->id])
            ->assertSuccessful()
            ->assertSessionHas('expanded_page_ids');

        $this->assertFalse(collect(session()->get('expanded_page_ids'))->contains($page->id));
    }

    public function test_pages_can_be_searched_for()
    {
        // we use this to search the page tree
        // since we dynamically load the page tree
        // for speed
        $parent = Page::factory()->create();
        $page = Page::factory()->create();
        $version = $page->versions->first();
        $version->parent_page_id = $parent->id;
        $version->save();

        $this->json('POST', route('pages.search-tree', []))
             ->assertStatus(401);

        $this->signInAdmin();
        $this->enableEditing();

        $this->json('POST', route('pages.search-tree', []))
             ->assertStatus(422)
             ->assertJsonValidationErrors([
                'terms',
             ]);

        $input = [
            'terms' => $page->getDraftVersion()->name,
        ];

        $this->assertTrue($page->parent_page_ids->contains($parent->id));

        $this->json('POST', route('pages.search-tree', $input))
             ->assertSuccessful();

        $this->assertTrue(collect(session()->get('expanded_page_ids'))->contains($parent->id));
    }
}
