<?php

declare(strict_types=1);

use App\Filament\Pages\EnvironmentDashboard;
use App\Http\Middleware\SuppressDebugbarForSmokeRequests;
use Barryvdh\Debugbar\LaravelDebugbar;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

uses(RefreshDatabase::class);

it('logs into the admin smoke helper with explicit tenant and workspace context', function (): void {
    [$user, $tenant] = createUserWithTenant(role: 'owner', workspaceRole: 'manager');

    $response = $this->get(route('admin.local.smoke-login', [
        'email' => $user->email,
        'tenant' => $tenant->external_id,
        'workspace' => $tenant->workspace->slug,
    ]));

    $response
        ->assertRedirect(EnvironmentDashboard::getUrl(tenant: $tenant))
        ->assertPlainCookie(
            SuppressDebugbarForSmokeRequests::COOKIE_NAME,
            SuppressDebugbarForSmokeRequests::COOKIE_VALUE,
        );

    $this->assertAuthenticatedAs($user);

    expect(session(App\Support\Workspaces\WorkspaceContext::SESSION_KEY))->toBe((int) $tenant->workspace_id)
        ->and(session(SuppressDebugbarForSmokeRequests::SESSION_KEY))
        ->toBe(SuppressDebugbarForSmokeRequests::COOKIE_VALUE)
        ->and(data_get(session(App\Support\Workspaces\WorkspaceContext::LAST_ENVIRONMENT_IDS_SESSION_KEY), (string) $tenant->workspace_id))
        ->toBe((int) $tenant->getKey());

    $this->get(EnvironmentDashboard::getUrl(tenant: $tenant))->assertSuccessful();
});

it('suppresses debugbar only for smoke-cookie requests and restores normal state afterward', function (): void {
    config(['debugbar.enabled' => true]);

    Route::middleware('web')->get('/__tests/smoke-debugbar-state', function () {
        $debugbarState = null;

        if (app()->bound('debugbar')) {
            $debugbar = app('debugbar');

            if ($debugbar instanceof LaravelDebugbar) {
                $debugbarState = $debugbar->isEnabled();
            }
        }

        return response()->json([
            'config_enabled' => (bool) config('debugbar.enabled'),
            'service_enabled' => $debugbarState,
        ]);
    });

    $smokeResponse = $this->withUnencryptedCookies([
        SuppressDebugbarForSmokeRequests::COOKIE_NAME => SuppressDebugbarForSmokeRequests::COOKIE_VALUE,
    ])->get('/__tests/smoke-debugbar-state');

    $smokeResponse
        ->assertSuccessful()
        ->assertJsonPath('config_enabled', false);

    if ($smokeResponse->json('service_enabled') !== null) {
        expect($smokeResponse->json('service_enabled'))->toBeFalse();
    }

    config(['debugbar.enabled' => true]);

    if (app()->bound('debugbar')) {
        $debugbar = app('debugbar');

        if ($debugbar instanceof LaravelDebugbar) {
            $debugbar->enable();
        }
    }

    $normalMiddlewareState = null;
    $middleware = app(SuppressDebugbarForSmokeRequests::class);

    $middleware->handle(Request::create('/admin/operations', 'GET'), function () use (&$normalMiddlewareState) {
        $normalMiddlewareState = config('debugbar.enabled');

        return response('ok');
    });

    expect($normalMiddlewareState)->toBeTrue();
});
