<?php

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

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

    $response = $this->actingAs($user)->postJson("/api/posts/{$post->id}/comments", [
        'content' => 'Great post!',
    ]);

    $response->assertStatus(201)
             ->assertJsonPath('comment.content', 'Great post!');

    $this->assertDatabaseHas('comments', ['content' => 'Great post!']);
});

test('guest cannot comment', function () {
    $post = Post::factory()->create();

    $this->postJson("/api/posts/{$post->id}/comments", ['content' => 'hi'])
         ->assertStatus(401);
});

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

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

test('user can get comments for a post', function () {
    $user    = User::factory()->create();
    $post    = Post::factory()->create();
    Comment::factory()->count(3)->create(['post_id' => $post->id]);

    $response = $this->actingAs($user)->getJson("/api/posts/{$post->id}/comments");

    $response->assertOk()
             ->assertJsonCount(3, 'data')
             ->assertJsonStructure(['data', 'meta', 'links']);
});
