<?php

use App\Domains\Workspace\Models\Workspace;
use App\Domains\Workspace\Models\WorkspaceMember;
use App\Models\User;

function makeUserWithWorkspace(): array
{
    $user = User::factory()->create();
    $ws = Workspace::factory()->create(['owner_id' => $user->id]);
    WorkspaceMember::create([
        'workspace_id' => $ws->id,
        'user_id' => $user->id,
        'role' => 'owner',
        'joined_at' => now(),
    ]);

    return [$user, $ws];
}

it('renders dashboard for workspace member', function () {
    [$user, $ws] = makeUserWithWorkspace();
    test()->actingAs($user)->get("/w/{$ws->ulid}")->assertOk();
});

it('renders links index', function () {
    [$user, $ws] = makeUserWithWorkspace();
    test()->actingAs($user)->get("/w/{$ws->ulid}/links")->assertOk();
});

it('renders qr index', function () {
    [$user, $ws] = makeUserWithWorkspace();
    test()->actingAs($user)->get("/w/{$ws->ulid}/qr")->assertOk();
});

it('renders bio index', function () {
    [$user, $ws] = makeUserWithWorkspace();
    test()->actingAs($user)->get("/w/{$ws->ulid}/bio")->assertOk();
});

it('renders domains index', function () {
    [$user, $ws] = makeUserWithWorkspace();
    test()->actingAs($user)->get("/w/{$ws->ulid}/domains")->assertOk();
});

it('renders analytics index', function () {
    [$user, $ws] = makeUserWithWorkspace();
    test()->actingAs($user)->get("/w/{$ws->ulid}/analytics")->assertOk();
});

it('renders billing index', function () {
    [$user, $ws] = makeUserWithWorkspace();
    test()->actingAs($user)->get("/w/{$ws->ulid}/billing")->assertOk();
});

it('renders team index', function () {
    [$user, $ws] = makeUserWithWorkspace();
    test()->actingAs($user)->get("/w/{$ws->ulid}/team")->assertOk();
});

it('renders settings index', function () {
    [$user, $ws] = makeUserWithWorkspace();
    test()->actingAs($user)->get("/w/{$ws->ulid}/settings")->assertOk();
});

it('rejects guest from workspace routes', function () {
    $owner = User::factory()->create();
    $ws = Workspace::factory()->create(['owner_id' => $owner->id]);
    test()->get("/w/{$ws->ulid}")->assertRedirect(route('login'));
});

it('rejects cross-workspace access', function () {
    [$user] = makeUserWithWorkspace();
    $otherOwner = User::factory()->create();
    $other = Workspace::factory()->create(['owner_id' => $otherOwner->id]);
    test()->actingAs($user)->get("/w/{$other->ulid}")->assertNotFound();
});
