<?php

declare(strict_types=1);

use App\Filament\Pages\Settings\WorkspaceSettings;
use App\Filament\System\Pages\Directory\ViewWorkspace;
use App\Models\PlatformUser;
use App\Models\ManagedEnvironment;
use App\Models\WorkspaceSubscription;
use App\Support\Auth\PlatformCapabilities;
use App\Support\Workspaces\WorkspaceContext;

pest()->browser()->timeout(20_000);

it('smokes subscription truth mutation on the system page', function (): void {
    $tenant = ManagedEnvironment::factory()->create([
        'name' => 'Browser Billing Truth ManagedEnvironment',
    ]);

    [$workspaceUser, $tenant] = createUserWithTenant(
        tenant: $tenant,
        role: 'owner',
        workspaceRole: 'owner',
        ensureDefaultMicrosoftProviderConnection: false,
    );

    $workspace = $tenant->workspace()->firstOrFail();

    $platformUser = PlatformUser::factory()->create([
        'capabilities' => [
            PlatformCapabilities::ACCESS_SYSTEM_PANEL,
            PlatformCapabilities::DIRECTORY_VIEW,
            PlatformCapabilities::COMMERCIAL_LIFECYCLE_MANAGE,
        ],
        'is_active' => true,
    ]);

    auth('web')->logout();
    $this->flushSession();
    $this->actingAs($platformUser, 'platform');

    $systemPage = visit(ViewWorkspace::getUrl(panel: 'system', parameters: ['workspace' => $workspace]));

    $systemPage
        ->waitForText('Workspace subscription')
        ->assertNoJavaScriptErrors()
        ->assertNoConsoleLogs()
        ->assertSee('fallback-backed')
        ->assertSee('Update subscription truth')
        ->click('Update subscription truth')
        ->waitForText('This records the current subscription-backed commercial truth for the workspace and becomes the upstream lifecycle source while the record exists.');

    $systemPage->script(<<<'JS'
(() => {
    const field = (labelText) => {
        const label = Array.from(document.querySelectorAll('label')).find((element) => element.textContent?.replace('*', '').trim() === labelText);

        if (! label) {
            return null;
        }

        const targetId = label.getAttribute('for');

        if (targetId) {
            return document.getElementById(targetId);
        }

        return label.parentElement?.querySelector('input, textarea, select') ?? null;
    };

    const state = field('Subscription state');
    const billingReference = field('Billing reference');
    const statusReason = field('Status reason');

    if (! state || ! billingReference || ! statusReason) {
        return false;
    }

    state.value = 'ended';
    state.dispatchEvent(new Event('change', { bubbles: true }));

    billingReference.value = 'sub_browser_truth_001';
    billingReference.dispatchEvent(new Event('input', { bubbles: true }));
    billingReference.dispatchEvent(new Event('change', { bubbles: true }));

    statusReason.value = 'Browser smoke recorded subscription truth.';
    statusReason.dispatchEvent(new Event('input', { bubbles: true }));
    statusReason.dispatchEvent(new Event('change', { bubbles: true }));

    return true;
})();
JS);

    $systemPage->script(<<<'JS'
(() => {
    const confirmButton = Array.from(document.querySelectorAll('button')).find((element) => element.textContent?.trim() === 'Confirm');

    confirmButton?.click();
})();
JS);

    $systemPage
        ->waitForText('subscription-backed')
        ->assertSee('Ended')
        ->assertNoJavaScriptErrors()
        ->assertNoConsoleLogs();
});

it('smokes the admin read-only commercial summary for subscription-backed truth', function (): void {
    $tenant = ManagedEnvironment::factory()->create([
        'name' => 'Browser Billing Summary ManagedEnvironment',
    ]);

    [$workspaceUser, $tenant] = createUserWithTenant(
        tenant: $tenant,
        role: 'owner',
        workspaceRole: 'owner',
        ensureDefaultMicrosoftProviderConnection: false,
    );

    $workspace = $tenant->workspace()->firstOrFail();

    WorkspaceSubscription::query()->create([
        'workspace_id' => (int) $workspace->getKey(),
        'state' => WorkspaceSubscription::STATE_ENDED,
        'billing_reference' => 'sub_browser_truth_001',
        'status_reason' => 'Browser smoke recorded subscription truth.',
    ]);

    $this->actingAs($workspaceUser)->withSession([
        WorkspaceContext::SESSION_KEY => (int) $workspace->getKey(),
    ]);
    session()->put(WorkspaceContext::SESSION_KEY, (int) $workspace->getKey());

    visit(WorkspaceSettings::getUrl(panel: 'admin'))
        ->waitForText('Commercial posture')
        ->assertNoJavaScriptErrors()
        ->assertNoConsoleLogs()
        ->assertSee('subscription-backed')
        ->assertSee('Ended')
        ->assertSee('Browser smoke recorded subscription truth.')
        ->assertDontSee('Update subscription truth');
});