<?php

use App\Models\ManagedEnvironment;
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 = ManagedEnvironment::factory()->create();

    [$owner] = createUserWithTenant($tenant, role: TenantRole::Owner->value);

    [$manager] = createUserWithTenant($tenant, role: TenantRole::Manager->value);

    [$readonly] = createUserWithTenant($tenant, role: TenantRole::Readonly->value);

    [$operator] = createUserWithTenant($tenant, role: TenantRole::Operator->value);

    $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->can($owner, $tenant, Capabilities::TENANT_ROLE_MAPPING_MANAGE))->toBeTrue();

    expect($resolver->isMember($manager, $tenant))->toBeTrue();
    expect($resolver->can($manager, $tenant, Capabilities::PROVIDER_MANAGE))->toBeTrue();
    expect($resolver->can($manager, $tenant, Capabilities::TENANT_BACKUP_SCHEDULES_MANAGE))->toBeTrue();
    expect($resolver->can($manager, $tenant, Capabilities::TENANT_BACKUP_SCHEDULES_RUN))->toBeTrue();
    expect($resolver->can($manager, $tenant, Capabilities::TENANT_MEMBERSHIP_MANAGE))->toBeFalse();
    expect($resolver->can($manager, $tenant, Capabilities::TENANT_ROLE_MAPPING_MANAGE))->toBeFalse();

    expect($resolver->isMember($operator, $tenant))->toBeTrue();
    expect($resolver->can($operator, $tenant, Capabilities::TENANT_BACKUP_SCHEDULES_RUN))->toBeTrue();
    expect($resolver->can($operator, $tenant, Capabilities::TENANT_BACKUP_SCHEDULES_MANAGE))->toBeFalse();

    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_BACKUP_SCHEDULES_RUN))->toBeFalse();
    expect($resolver->can($readonly, $tenant, Capabilities::TENANT_BACKUP_SCHEDULES_MANAGE))->toBeFalse();
    expect($resolver->can($readonly, $tenant, Capabilities::TENANT_MEMBERSHIP_MANAGE))->toBeFalse();

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

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