<?php

use App\Models\Artwork;
use App\Models\ArtworkComment;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

test('posting an artwork comment updates artwork stats comments count immediately', function () {
    $commenter = User::factory()->create();
    $artwork = Artwork::factory()->create([
        'is_public' => true,
        'is_approved' => true,
        'published_at' => now()->subHour(),
    ]);

    $this->actingAs($commenter)
        ->postJson("/api/artworks/{$artwork->id}/comments", [
            'content' => 'Realtime analytics check.',
        ])
        ->assertStatus(201);

    $this->assertDatabaseHas('artwork_stats', [
        'artwork_id' => $artwork->id,
        'comments_count' => 1,
    ]);
});

test('deleting an artwork comment updates artwork stats comments count immediately', function () {
    $commenter = User::factory()->create();
    $artwork = Artwork::factory()->create([
        'is_public' => true,
        'is_approved' => true,
        'published_at' => now()->subHour(),
    ]);

    $comment = ArtworkComment::factory()->create([
        'artwork_id' => $artwork->id,
        'user_id' => $commenter->id,
        'is_approved' => true,
    ]);

    $this->assertDatabaseHas('artwork_stats', [
        'artwork_id' => $artwork->id,
        'comments_count' => 1,
    ]);

    $this->actingAs($commenter)
        ->deleteJson("/api/artworks/{$artwork->id}/comments/{$comment->id}")
        ->assertOk();

    $this->assertDatabaseHas('artwork_stats', [
        'artwork_id' => $artwork->id,
        'comments_count' => 0,
    ]);
});

test('sharing an artwork updates artwork stats shares count immediately', function () {
    $user = User::factory()->create();
    $artwork = Artwork::factory()->create();

    $this->actingAs($user)
        ->postJson("/api/artworks/{$artwork->id}/share", [
            'platform' => 'copy',
        ])
        ->assertOk()
        ->assertJsonPath('ok', true);

    $this->assertDatabaseHas('artwork_shares', [
        'artwork_id' => $artwork->id,
        'user_id' => $user->id,
        'platform' => 'copy',
    ]);

    $this->assertDatabaseHas('artwork_stats', [
        'artwork_id' => $artwork->id,
        'shares_count' => 1,
    ]);
});