<?php

declare(strict_types=1);

use App\Models\Tenant;
use App\Services\Auth\WorkspaceRoleCapabilityMap;
use App\Support\Auth\Capabilities;

it('registers managed tenant onboarding wizard capabilities in the canonical registry', function (): void {
    expect(Capabilities::isKnown(Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_IDENTIFY))->toBeTrue();
    expect(Capabilities::isKnown(Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_CONNECTION_VIEW))->toBeTrue();
    expect(Capabilities::isKnown(Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_CONNECTION_MANAGE))->toBeTrue();
    expect(Capabilities::isKnown(Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_VERIFICATION_START))->toBeTrue();
    expect(Capabilities::isKnown(Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_INVENTORY_SYNC))->toBeTrue();
    expect(Capabilities::isKnown(Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_POLICY_SYNC))->toBeTrue();
    expect(Capabilities::isKnown(Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_BOOTSTRAP_BACKUP_BOOTSTRAP))->toBeTrue();
    expect(Capabilities::isKnown(Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_ACTIVATE))->toBeTrue();
});

it('maps onboarding wizard capabilities to workspace roles (least privilege)', function (): void {
    expect(WorkspaceRoleCapabilityMap::hasCapability('owner', Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_IDENTIFY))->toBeTrue();
    expect(WorkspaceRoleCapabilityMap::hasCapability('manager', Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_IDENTIFY))->toBeTrue();
    expect(WorkspaceRoleCapabilityMap::hasCapability('operator', Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_IDENTIFY))->toBeFalse();
    expect(WorkspaceRoleCapabilityMap::hasCapability('readonly', Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_IDENTIFY))->toBeFalse();

    expect(WorkspaceRoleCapabilityMap::hasCapability('owner', Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_ACTIVATE))->toBeTrue();
    expect(WorkspaceRoleCapabilityMap::hasCapability('manager', Capabilities::WORKSPACE_MANAGED_TENANT_ONBOARD_ACTIVATE))->toBeFalse();
});

it('supports the v1 managed tenant lifecycle statuses', function (): void {
    $draft = Tenant::factory()->create(['status' => Tenant::STATUS_DRAFT]);
    $onboarding = Tenant::factory()->create(['status' => Tenant::STATUS_ONBOARDING]);
    $active = Tenant::factory()->create(['status' => Tenant::STATUS_ACTIVE]);

    expect(Tenant::activeQuery()->pluck('id')->all())->toContain((int) $active->getKey());
    expect(Tenant::activeQuery()->pluck('id')->all())->not->toContain((int) $draft->getKey());
    expect(Tenant::activeQuery()->pluck('id')->all())->not->toContain((int) $onboarding->getKey());

    $onboarding->delete();
    $onboarding->refresh();

    expect($onboarding->status)->toBe(Tenant::STATUS_ARCHIVED);

    $onboarding->restore();
    $onboarding->refresh();

    expect($onboarding->status)->toBe(Tenant::STATUS_ACTIVE);
});
