<?php

use App\Events\NewEmailReceived;
use App\Jobs\ProcessIncomingEmail;
use App\Models\Email;
use App\Models\EmailBody;
use Illuminate\Support\Facades\Event;

it('stores incoming email in MariaDB and MongoDB, and broadcasts event', function () {
    Event::fake();

    $hash = 'test-hash-'.time();
    $payload = [
        'hash' => $hash,
        'metadata' => [
            'recipientEmail' => 'test@imail.app',
            'recipientName' => 'Test User',
            'senderEmail' => 'sender@example.com',
            'senderName' => 'Sender Name',
            'domain' => 'imail.app',
            'subject' => 'Test Subject',
            'received_at' => now()->toIso8601String(),
            'attachmentSize' => 1024,
            'attachments' => [
                ['filename' => 'test.pdf', 'mimeType' => 'application/pdf', 'size' => 1024],
            ],
        ],
        'bodyText' => 'This is the plain text body format.',
        'bodyHtml' => '<html><body><p>This is the HTML body format.</p></body></html>',
    ];

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

    // Verify MariaDB storage
    $this->assertDatabaseHas('emails', [
        'unique_id_hash' => $hash,
        'recipient_email' => 'test@imail.app',
        'domain' => 'imail.app',
        'subject' => 'Test Subject',
        'preview' => 'This is the plain text body format.',
        'attachment_size' => 1024,
    ]);

    $email = Email::where('unique_id_hash', $hash)->first();
    expect($email->attachments_json)->toHaveCount(1)
        ->and($email->attachments_json[0]['filename'])->toBe('test.pdf');

    // Verify MongoDB storage
    $body = EmailBody::where('unique_id_hash', $hash)->first();
    expect($body)->not->toBeNull()
        ->and($body->body_text)->toBe('This is the plain text body format.')
        ->and($body->body_html)->toBe('<html><body><p>This is the HTML body format.</p></body></html>');

    // Verify Broadcast Event
    Event::assertDispatched(NewEmailReceived::class, function ($event) use ($hash) {
        return $event->email->unique_id_hash === $hash;
    });

    // Cleanup MongoDB (MariaDB is handled by RefreshDatabase if used, but let's be safe)
    $body->delete();
});

it('generates preview from stripped HTML if text body is missing', function () {
    Event::fake();

    $hash = 'test-hash-html-only-'.time();
    $payload = [
        'hash' => $hash,
        'metadata' => [
            'recipientEmail' => 'test2@imail.app',
            'senderEmail' => 'sender2@example.com',
            'domain' => 'imail.app',
            'received_at' => now()->toIso8601String(),
        ],
        'bodyText' => null,
        'bodyHtml' => '<html><body><h1>Welcome</h1><p>This is a <strong>strong</strong> test.</p>   <br> <p>Footer</p></body></html>',
    ];

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

    // Verify MariaDB storage preview logic
    $this->assertDatabaseHas('emails', [
        'unique_id_hash' => $hash,
        'preview' => 'Welcome This is a strong test. Footer',
    ]);

    // Cleanup MongoDB
    EmailBody::where('unique_id_hash', $hash)->delete();
});
