<?php

use App\Domains\Link\Models\Link;
use App\Domains\Workspace\Actions\CreateWorkspace;
use App\Models\User;

it('lists links for authenticated workspace', function () {
    $user = User::factory()->create();
    $workspace = (new CreateWorkspace)->handle($user, ['name' => 'Test']);
    Link::factory()->count(3)->create(['workspace_id' => $workspace->id]);

    $token = $user->createToken('api-test')->plainTextToken;

    $response = $this->withToken($token)
        ->getJson("/api/v1/workspaces/{$workspace->ulid}/links");

    $response->assertOk()
        ->assertJsonCount(3, 'data');
});

it('creates link via API', function () {
    $user = User::factory()->create();
    $workspace = (new CreateWorkspace)->handle($user, ['name' => 'Test']);
    $token = $user->createToken('api-test')->plainTextToken;

    $response = $this->withToken($token)
        ->postJson("/api/v1/workspaces/{$workspace->ulid}/links", [
            'target_url' => 'https://example.com',
        ]);

    $response->assertCreated()
        ->assertJsonPath('data.target_url', 'https://example.com');
});

it('deletes a link via API', function () {
    $user = User::factory()->create();
    $workspace = (new CreateWorkspace)->handle($user, ['name' => 'Test']);
    $link = Link::factory()->create(['workspace_id' => $workspace->id]);
    $token = $user->createToken('api-test')->plainTextToken;

    $response = $this->withToken($token)
        ->deleteJson("/api/v1/workspaces/{$workspace->ulid}/links/{$link->ulid}");

    $response->assertNoContent();
    $this->assertSoftDeleted($link);
});

it('rejects delete from non-member', function () {
    $owner = User::factory()->create();
    $outsider = User::factory()->create();
    $workspace = (new CreateWorkspace)->handle($owner, ['name' => 'Test']);
    $link = Link::factory()->create(['workspace_id' => $workspace->id]);
    $token = $outsider->createToken('api-test')->plainTextToken;

    $response = $this->withToken($token)
        ->deleteJson("/api/v1/workspaces/{$workspace->ulid}/links/{$link->ulid}");

    $response->assertForbidden();
});

it('rejects unauthenticated requests', function () {
    $response = $this->getJson('/api/v1/workspaces/ULID/links');
    $response->assertUnauthorized();
});
