<?php

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

test('authenticated user can list replies for a comment', function () {
    $user    = User::factory()->create();
    $comment = Comment::factory()->create();
    Reply::factory()->count(3)->create(['comment_id' => $comment->id]);

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

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

test('authenticated user can reply to a comment', function () {
    $user    = User::factory()->create();
    $post    = Post::factory()->create();
    $comment = Comment::factory()->create(['post_id' => $post->id]);

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

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

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

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

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

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

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

test('user can delete their own reply', function () {
    $user  = User::factory()->create();
    $reply = Reply::factory()->create(['user_id' => $user->id]);

    $this->actingAs($user)
         ->deleteJson("/api/replies/{$reply->id}")
         ->assertOk()
         ->assertJsonPath('message', 'Reply deleted.');

    $this->assertSoftDeleted('replies', ['id' => $reply->id]);
});
