<?php

use App\Jobs\TrackAnalytics;
use App\Models\AnalyticsEvent;
use Illuminate\Support\Facades\Queue;

test('TrackAnalytics job records event in MongoDB', function () {
    // We don't fake the queue here because we want to run the job
    // synchronously to verify MongoDB storage.

    $eventData = [
        'eventType' => 'test_event',
        'mailboxHash' => 'test-mailbox-hash',
        'domainHash' => 'test-domain-hash',
        'metadata' => ['foo' => 'bar'],
        'userId' => 123,
        'userType' => 'authenticated',
        'ipAddress' => '1.2.3.4',
        'userAgent' => 'TestAgent',
    ];

    $job = new TrackAnalytics(
        ...$eventData
    );

    $job->handle();

    // Verify MongoDB storage
    $event = AnalyticsEvent::where('mailbox_hash', 'test-mailbox-hash')
        ->where('event_type', 'test_event')
        ->first();

    expect($event)->not->toBeNull()
        ->and($event->event_type)->toBe('test_event')
        ->and($event->mailbox_hash)->toBe('test-mailbox-hash')
        ->and($event->domain_hash)->toBe('test-domain-hash')
        ->and($event->user_id)->toBe(123)
        ->and($event->user_type)->toBe('authenticated')
        ->and($event->ip_address)->toBe('1.2.3.4')
        ->and($event->user_agent)->toBe('TestAgent')
        ->and($event->metadata)->toBe(['foo' => 'bar']);

    // Cleanup
    $event->delete();
});
