<?php

use App\Events\NewEmailReceived;
use App\Jobs\ProcessIncomingEmail;
use App\Models\Domain;
use App\Models\Email;
use App\Models\EmailBody;
use App\Models\Mailbox;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Queue;

test('it processes incoming email and tracks analytics', function () {
    Event::fake();
    Queue::fake();

    $domain = Domain::factory()->create([
        'name' => 'test-ingestion.com',
    ]);

    $mailbox = Mailbox::factory()->create([
        'address' => 'user@test-ingestion.com',
        'domain_hash' => $domain->domain_hash,
    ]);

    Log::info('Mailbox created in test', [
        'id' => $mailbox->id,
        'address' => $mailbox->address,
        'domain_hash' => $mailbox->domain_hash,
    ]);

    $hash = 'ingestion-hash-'.uniqid();
    $payload = [
        'hash' => $hash,
        'metadata' => [
            'recipientEmail' => 'user@test-ingestion.com',
            'senderEmail' => 'sender@other.com',
            'domain' => 'test-ingestion.com',
            'subject' => 'Integration Test',
            'received_at' => now()->toIso8601String(),
        ],
        'bodyText' => 'Testing ingestion.',
        'bodyHtml' => '<p>Testing ingestion.</p>',
    ];

    Log::info('Mailboxes in DB before job', ['count' => Mailbox::count(), 'addresses' => Mailbox::pluck('address')->toArray()]);

    $job = new ProcessIncomingEmail($payload);
    $job->handle();

    // MariaDB Email record
    $this->assertDatabaseHas('emails', [
        'unique_id_hash' => $hash,
        'recipient_email' => 'user@test-ingestion.com',
    ]);

    // Analytics Job
    Queue::assertPushed(\App\Jobs\TrackAnalytics::class, function ($job) use ($mailbox) {
        return $job->eventType === 'email_received' && $job->mailboxHash === $mailbox->mailbox_hash;
    });

    // MongoDB Body
    $body = EmailBody::where('unique_id_hash', $hash)->first();
    expect($body)->not->toBeNull()
        ->and($body->body_text)->toBe('Testing ingestion.');

    // Event
    Event::assertDispatched(NewEmailReceived::class);

    $body->delete();
});

test('it handles emails for unknown mailboxes without failing', function () {
    Event::fake();
    Queue::fake();

    $hash = 'unknown-hash-'.uniqid();
    $payload = [
        'hash' => $hash,
        'metadata' => [
            'recipientEmail' => 'nonexistent@test-ingestion.com',
            'senderEmail' => 'sender@other.com',
            'domain' => 'test-ingestion.com',
            'received_at' => now()->toIso8601String(),
        ],
        'bodyText' => 'Testing unknown.',
    ];

    $job = new ProcessIncomingEmail($payload);
    $job->handle();

    $this->assertDatabaseHas('emails', [
        'unique_id_hash' => $hash,
    ]);

    Queue::assertPushed(\App\Jobs\TrackAnalytics::class, function ($job) {
        return $job->mailboxHash === 'unknown';
    });
});
