<?php

declare(strict_types=1);

use App\Models\Workspace;
use App\Support\Workspaces\WorkspaceResolver;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

it('resolves a workspace by slug or id', function (): void {
    $workspace = Workspace::factory()->create([
        'slug' => 'resolver-smoke-workspace',
    ]);

    $resolver = app(WorkspaceResolver::class);

    expect($resolver->resolve('resolver-smoke-workspace')?->is($workspace))->toBeTrue()
        ->and($resolver->resolve((string) $workspace->getKey())?->is($workspace))->toBeTrue();
});

it('resolves a Livewire serialized workspace route parameter', function (): void {
    $workspace = Workspace::factory()->create([
        'slug' => 'serialized-route-workspace',
    ]);

    $payload = json_encode([
        'id' => $workspace->getKey(),
        'name' => $workspace->name,
        'slug' => $workspace->slug,
    ], JSON_THROW_ON_ERROR);

    expect(app(WorkspaceResolver::class)->resolve($payload)?->is($workspace))->toBeTrue();
});

it('falls back to serialized id when a Livewire route payload has no slug', function (): void {
    $workspace = Workspace::factory()->create();

    $payload = json_encode([
        'id' => (string) $workspace->getKey(),
    ], JSON_THROW_ON_ERROR);

    expect(app(WorkspaceResolver::class)->resolve($payload)?->is($workspace))->toBeTrue();
});

it('returns null for an unsupported serialized route payload', function (): void {
    $payload = json_encode([
        'name' => 'Missing key',
    ], JSON_THROW_ON_ERROR);

    expect(app(WorkspaceResolver::class)->resolve($payload))->toBeNull();
});
