<?php

namespace Tests\Feature;

use App\Models\User;
use App\Models\Notification;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class NotificationTest extends TestCase
{
    use RefreshDatabase;

    public function test_user_can_fetch_their_notifications(): void
    {
        $user = User::factory()->create();
        
        Notification::notify($user->id, 'success', 'Test Success', 'A test message', '/contacts');
        Notification::notify($user->id, 'error', 'Test Error', 'An error message');

        $response = $this->actingAs($user)->getJson(route('notifications.index'));

        $response->assertStatus(200)
            ->assertJsonCount(2, 'notifications')
            ->assertJsonFragment(['title' => 'Test Success'])
            ->assertJsonFragment(['title' => 'Test Error'])
            ->assertJson([
                'unreadCount' => 2
            ]);
    }

    public function test_user_can_mark_notification_as_read(): void
    {
        $user = User::factory()->create();
        $notification = Notification::notify($user->id, 'success', 'Test Success', 'A test message');

        $response = $this->actingAs($user)->postJson(route('notifications.read', $notification->id));

        $response->assertStatus(200);
        $this->assertNotNull($notification->fresh()->read_at);
    }

    public function test_user_can_mark_all_notifications_as_read(): void
    {
        $user = User::factory()->create();
        Notification::notify($user->id, 'success', 'Test 1', 'Msg 1');
        Notification::notify($user->id, 'info', 'Test 2', 'Msg 2');

        $response = $this->actingAs($user)->postJson(route('notifications.read-all'));

        $response->assertStatus(200);
        $this->assertEquals(0, $user->notifications()->whereNull('read_at')->count());
    }

    public function test_user_can_clear_all_notifications(): void
    {
        $user = User::factory()->create();
        Notification::notify($user->id, 'success', 'Test 1', 'Msg 1');

        $response = $this->actingAs($user)->deleteJson(route('notifications.clear'));

        $response->assertStatus(200);
        $this->assertEquals(0, $user->notifications()->count());
    }
}
