<?php

use App\Jobs\TrackAnalytics;
use App\Models\Domain;
use App\Models\Mailbox;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Queue;

uses(Tests\TestCase::class, RefreshDatabase::class);

test('mailbox hash is automatically generated on creation', function () {
    Queue::fake();

    $domain = Domain::factory()->create();
    $mailbox = Mailbox::factory()->create([
        'domain_hash' => $domain->domain_hash,
        'address' => 'hash-test@'.$domain->name,
    ]);

    expect($mailbox->mailbox_hash)->not->toBeNull()
        ->and(strlen($mailbox->mailbox_hash))->toBeGreaterThan(20);
});

test('TrackAnalytics job is dispatched on mailbox creation', function () {
    Queue::fake();

    $mailbox = Mailbox::factory()->create();

    Queue::assertPushed(TrackAnalytics::class, function ($job) use ($mailbox) {
        return $job->eventType === 'mailbox_created' &&
               $job->mailboxHash === $mailbox->mailbox_hash;
    });
});

test('mailbox relationships work correctly', function () {
    Queue::fake();

    $user = User::factory()->create();
    $domain = Domain::factory()->create();
    $mailbox = Mailbox::factory()->create([
        'user_id' => $user->id,
        'domain_hash' => $domain->domain_hash,
    ]);

    expect($mailbox->user->id)->toBe($user->id)
        ->and($mailbox->domain->domain_hash)->toBe($domain->domain_hash);
});

test('mailbox casts dates and booleans correctly', function () {
    Queue::fake();

    $mailbox = Mailbox::factory()->create([
        'expires_at' => now()->addHours(2),
        'is_blocked' => 1,
        'blocked_at' => now()->subMinute(),
    ]);

    expect($mailbox->expires_at)->toBeInstanceOf(\Illuminate\Support\Carbon::class)
        ->and($mailbox->is_blocked)->toBeTrue()
        ->and($mailbox->blocked_at)->toBeInstanceOf(\Illuminate\Support\Carbon::class);
});
