<?php

namespace Ignite\Core\Tests\Unit\Entities;

use Ignite\Core\Entities\Block;
use Ignite\Core\Entities\Participant;
use Ignite\Core\Tests\TestCase;
use Ignite\Core\Tests\Unit\Entities\Filters\DummyParticipantPermissionFilter;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Config;

class BaseTest extends TestCase
{
    use RefreshDatabase;

    /** @test */
    public function entities_can_be_filtered_based_on_user_permission()
    {
        // Arrange
        Config::set('core.query_filters.permissions', [
            'core.user.participant.browse' => DummyParticipantPermissionFilter::class,
            'core.user.participant.update' => DummyParticipantPermissionFilter::class,
        ]);
        $this->actingAs(factory(Participant::class)->create(['state' => 'TX', 'type' => 'Account Executive'])->user);
        $user1 = factory(Participant::class)->create(['state' => 'NM', 'type' => 'Account Executive'])->user;
        factory(Participant::class)->times(4)->create(['type' => 'Type1']);
        factory(Participant::class)->times(2)->create(['type' => 'Type2']);
        factory(Participant::class)->times(1)->create(['type' => 'Type3']);

        // Execute & Check
        $this->assertEquals(
            7,
            Participant::query()->whereHasPermission('core.user.participant.browse')->count(),
            'Authed user can only browse/read type1, type2 & their self.'
        );
        $this->assertEquals(
            9,
            Participant::query()->whereHasPermission('core.user.participant.delete')->count(),
            'No associated permissions class, so able to delete any user!'
        );
        $this->assertEquals(
            2,
            Participant::query()->whereHasPermission('core.user.participant.browse', $user1)->count(),
            'Given user can only browse/read type3 and their self.'
        );
    }

    /** @test */
    public function cannot_scope_an_entity_with_a_scoped_permissions_class_for_another_entity()
    {
        // Arrange
        Config::set('core.query_filters.permissions', [
            'core.user.participant.browse' => DummyParticipantPermissionFilter::class,
        ]);
        $this->actingAs(factory(Participant::class)->create(['state' => 'TX', 'type' => 'Account Executive'])->user);

        // Set Expectation
        $this->expectException(\LogicException::class);

        // Execute
        Block::query()->whereHasPermission('core.user.participant.browse')->count();
    }
}
