<?php

declare(strict_types=1);

namespace Tests\Feature;

use App\Models\Category;
use App\Models\Log;
use App\Models\Session;
use App\Models\User;
use App\Services\ActivityLogger;
use Tests\TestCase;

class ActivityLoggerTest extends TestCase
{
    public function test_creates_record_with_all_fields(): void
    {
        $user = User::factory()->create();
        $category = Category::factory()->create();
        $session = Session::factory()->create([
            'user_id' => $user->id,
            'category_id' => $category->id,
        ]);

        $metadata = ['key' => 'value', 'count' => 42];

        ActivityLogger::log(
            action: 'test_action',
            userId: $user->id,
            sessionId: $session->id,
            categoryId: $category->id,
            metadata: $metadata
        );

        $this->assertDatabaseHas('logs', [
            'user_id' => $user->id,
            'session_id' => $session->id,
            'category_id' => $category->id,
            'action' => 'test_action',
        ]);

        $log = Log::where('action', 'test_action')->first();

        $this->assertEquals($metadata, $log->metadata);
    }

    public function test_creates_record_with_minimal_fields(): void
    {
        ActivityLogger::log(action: 'minimal_action');

        $this->assertDatabaseHas('logs', [
            'user_id' => null,
            'session_id' => null,
            'category_id' => null,
            'action' => 'minimal_action',
        ]);

        $log = Log::where('action', 'minimal_action')->first();

        $this->assertNull($log->metadata);
    }

    public function test_log_model_prevents_updates(): void
    {
        $log = Log::factory()->create([
            'action' => 'original_action',
        ]);

        $log->action = 'updated_action';
        $log->save();

        $log->refresh();

        $this->assertEquals('original_action', $log->action);
    }

    public function test_log_model_prevents_deletes(): void
    {
        $log = Log::factory()->create([
            'action' => 'test_delete',
        ]);

        $logId = $log->id;

        $log->delete();

        $this->assertDatabaseHas('logs', [
            'id' => $logId,
            'action' => 'test_delete',
        ]);
    }
}
