<?php

use App\Models\Tenant;
use App\Models\User;
use App\Services\Auth\CapabilityResolver;
use App\Support\Auth\Capabilities;
use App\Support\TenantRole;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('resolves membership and capabilities deterministically', function () {
    $tenant = Tenant::factory()->create();

    $owner = User::factory()->create();
    $owner->tenants()->attach($tenant->getKey(), ['role' => TenantRole::Owner->value, 'source' => 'manual']);

    $readonly = User::factory()->create();
    $readonly->tenants()->attach($tenant->getKey(), ['role' => TenantRole::Readonly->value, 'source' => 'manual']);

    $resolver = app(CapabilityResolver::class);

    expect($resolver->isMember($owner, $tenant))->toBeTrue();
    expect($resolver->can($owner, $tenant, Capabilities::PROVIDER_MANAGE))->toBeTrue();
    expect($resolver->can($owner, $tenant, Capabilities::TENANT_MEMBERSHIP_MANAGE))->toBeTrue();

    expect($resolver->isMember($readonly, $tenant))->toBeTrue();
    expect($resolver->can($readonly, $tenant, Capabilities::PROVIDER_VIEW))->toBeTrue();
    expect($resolver->can($readonly, $tenant, Capabilities::PROVIDER_MANAGE))->toBeFalse();
    expect($resolver->can($readonly, $tenant, Capabilities::TENANT_MEMBERSHIP_MANAGE))->toBeFalse();

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

    expect($resolver->isMember($outsider, $tenant))->toBeFalse();
    expect($resolver->can($outsider, $tenant, Capabilities::PROVIDER_VIEW))->toBeFalse();
});
