<?php

app_require('classes/email.php');

use classes\email;

it('syncs fake email deliveries written by another process', function (): void {
    $previousFakeMode = getenv('EMAIL_FAKE_MODE');
    $previousFakePath = getenv('EMAIL_FAKE_DELIVERIES_PATH');
    $path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'truckwash-fake-email-sync-' . bin2hex(random_bytes(4)) . '.jsonl';

    putenv('EMAIL_FAKE_MODE=1');
    putenv('EMAIL_FAKE_DELIVERIES_PATH=' . $path);
    email::resetFakeDeliveries();

    try {
        file_put_contents($path, json_encode([
            'to' => 'customer@example.test',
            'recipient_name' => 'Customer',
            'subject' => 'Subject',
            'message' => '',
            'html' => '<p>Body</p>',
        ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL);

        email::syncFakeDeliveries();

        expect(email::$fake_deliveries)
            ->toHaveCount(1)
            ->and(email::$fake_deliveries[0]['to'] ?? null)
            ->toBe('customer@example.test')
            ->and(email::$fake_deliveries[0]['subject'] ?? null)
            ->toBe('Subject');
    } finally {
        email::resetFakeDeliveries();
        if (is_file($path)) {
            unlink($path);
        }
        if ($previousFakeMode === false) {
            putenv('EMAIL_FAKE_MODE');
        } else {
            putenv('EMAIL_FAKE_MODE=' . $previousFakeMode);
        }
        if ($previousFakePath === false) {
            putenv('EMAIL_FAKE_DELIVERIES_PATH');
        } else {
            putenv('EMAIL_FAKE_DELIVERIES_PATH=' . $previousFakePath);
        }
    }
});
