<?php

use App\Models\Post;
use App\Models\User;

test('authenticated user can create a post', function () {
    $user = User::factory()->create();

    $response = $this->actingAs($user)->postJson('/api/posts', [
        'content'    => 'Hello world',
        'visibility' => 'public',
    ]);

    $response->assertStatus(201)
             ->assertJsonPath('post.content', 'Hello world');

    $this->assertDatabaseHas('posts', ['content' => 'Hello world']);
});

test('guest cannot create a post', function () {
    $this->postJson('/api/posts', ['content' => 'test', 'visibility' => 'public'])
         ->assertStatus(401);
});

test('user cannot update another user\'s post', function () {
    $owner = User::factory()->create();
    $other = User::factory()->create();
    $post  = Post::factory()->create(['user_id' => $owner->id]);

    $this->actingAs($other)
         ->putJson("/api/posts/{$post->id}", ['content' => 'hacked'])
         ->assertStatus(403);
});

test('private post is not visible to other users', function () {
    $owner = User::factory()->create();
    $other = User::factory()->create();
    Post::factory()->create([
        'user_id'    => $owner->id,
        'visibility' => 'private',
    ]);

    $response = $this->actingAs($other)->getJson('/api/posts');

    $response->assertOk();
    $this->assertCount(0, $response->json('data'));
});
