<?php

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

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

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

    $response->assertOk()
             ->assertJsonPath('liked', true)
             ->assertJsonPath('like_count', 1);

    $this->assertDatabaseHas('likes', [
        'user_id'       => $user->id,
        'likeable_type' => 'App\Models\Post',
        'likeable_id'   => $post->id,
    ]);
});

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

    // First like
    $this->actingAs($user)->postJson("/api/posts/{$post->id}/like");

    // Then unlike
    $response = $this->actingAs($user)->postJson("/api/posts/{$post->id}/like");

    $response->assertOk()
             ->assertJsonPath('liked', false)
             ->assertJsonPath('like_count', 0);

    $this->assertDatabaseMissing('likes', [
        'user_id'       => $user->id,
        'likeable_type' => 'App\Models\Post',
        'likeable_id'   => $post->id,
    ]);
});

test('user can like a comment', function () {
    $user    = User::factory()->create();
    $comment = Comment::factory()->create();

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

    $response->assertOk()
             ->assertJsonPath('liked', true)
             ->assertJsonPath('like_count', 1);
});

test('user can like a reply', function () {
    $user  = User::factory()->create();
    $reply = Reply::factory()->create();

    $response = $this->actingAs($user)->postJson("/api/replies/{$reply->id}/like");

    $response->assertOk()
             ->assertJsonPath('liked', true)
             ->assertJsonPath('like_count', 1);
});

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

    $this->postJson("/api/posts/{$post->id}/like")
         ->assertStatus(401);
});
