<?php

namespace Tests\Unit\Listeners;

use App\Enums\LogLevelEnum;
use App\Events\ActionPerformed;
use App\Listeners\LogActionListener;
use App\Models\Log;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class LogActionListenerTest extends TestCase
{
    use RefreshDatabase;

    public function test_listener_creates_log_entry_with_correct_data(): void
    {
        $event = new ActionPerformed(
            'Article published successfully',
            LogLevelEnum::INFO,
            ['article_id' => 42],
        );

        $listener = app(LogActionListener::class);
        $listener->handle($event);

        $this->assertDatabaseHas('logs', [
            'level' => 'info',
            'message' => 'Article published successfully',
        ]);

        $log = Log::where('message', 'Article published successfully')->first();
        $this->assertEquals(['article_id' => 42], $log->context);
    }

    public function test_listener_creates_log_with_warning_level(): void
    {
        $event = new ActionPerformed(
            'No publications created',
            LogLevelEnum::WARNING,
            ['article_id' => 7],
        );

        $listener = app(LogActionListener::class);
        $listener->handle($event);

        $this->assertDatabaseHas('logs', [
            'level' => 'warning',
            'message' => 'No publications created',
        ]);
    }

    public function test_listener_creates_log_with_error_level(): void
    {
        $event = new ActionPerformed(
            'Publishing failed',
            LogLevelEnum::ERROR,
            ['error' => 'Connection timeout'],
        );

        $listener = app(LogActionListener::class);
        $listener->handle($event);

        $this->assertDatabaseHas('logs', [
            'level' => 'error',
            'message' => 'Publishing failed',
        ]);
    }

    public function test_listener_creates_log_with_empty_context(): void
    {
        $event = new ActionPerformed('Simple action');

        $listener = app(LogActionListener::class);
        $listener->handle($event);

        $this->assertDatabaseHas('logs', [
            'level' => 'info',
            'message' => 'Simple action',
        ]);

        $log = Log::where('message', 'Simple action')->first();
        $this->assertEquals([], $log->context);
    }
}
