<?php

declare(strict_types=1);

use App\Models\Artwork;
use App\Models\ArtworkComment;
use App\Models\User;
use App\Services\ReceivedCommentsInboxService;
use Illuminate\Support\Carbon;

it('tracks unread received comments and clears them when the inbox is opened', function () {
    Carbon::setTestNow('2026-03-19 12:00:00');

    $owner = User::factory()->create();
    $commenter = User::factory()->create();

    $artwork = Artwork::factory()->create([
        'user_id' => $owner->id,
        'is_approved' => true,
        'is_public' => true,
        'published_at' => now()->subDay(),
    ]);

    $firstComment = ArtworkComment::factory()->create([
        'artwork_id' => $artwork->id,
        'user_id' => $commenter->id,
        'content' => 'First unread comment',
        'raw_content' => 'First unread comment',
        'rendered_content' => '<p>First unread comment</p>',
        'is_approved' => true,
        'created_at' => now()->subMinute(),
        'updated_at' => now()->subMinute(),
    ]);

    $service = app(ReceivedCommentsInboxService::class);

    expect($service->unreadCountForUser($owner))->toBe(1);

    $this->actingAs($owner)
        ->get('/dashboard/comments/received')
        ->assertOk()
        ->assertSee('Marked 1 new comment as read', false);

    $this->assertDatabaseHas('user_received_comment_reads', [
        'user_id' => $owner->id,
        'artwork_comment_id' => $firstComment->id,
    ]);
    expect($service->unreadCountForUser($owner))->toBe(0);

    Carbon::setTestNow('2026-03-19 12:05:00');

    ArtworkComment::factory()->create([
        'artwork_id' => $artwork->id,
        'user_id' => $commenter->id,
        'content' => 'Second unread comment',
        'raw_content' => 'Second unread comment',
        'rendered_content' => '<p>Second unread comment</p>',
        'is_approved' => true,
        'created_at' => now(),
        'updated_at' => now(),
    ]);

    expect($service->unreadCountForUser($owner))->toBe(1);

    Carbon::setTestNow();
});
