<?php

declare(strict_types=1);

require __DIR__ . '/../app/saas-mail.php';

function mail_check_assert(string $label, bool $condition, array &$failures, int &$passes): void
{
    if ($condition) {
        $passes++;
        echo "PASS {$label}\n";
        return;
    }

    $failures[] = $label;
    echo "FAIL {$label}\n";
}

$logDir = APP_ROOT . '/var/test-mail';
if (!is_dir($logDir)) {
    mkdir($logDir, 0700, true);
}

foreach (glob($logDir . '/*.txt') ?: [] as $file) {
    unlink($file);
}

putenv('APP_MAIL_TRANSPORT=log');
putenv('APP_MAIL_LOG_DIR=' . $logDir);
putenv('APP_BASE_URL=https://app.example.test');
putenv('APP_MAIL_FROM=noreply@example.test');
putenv('APP_MAIL_FROM_NAME=Kaffeeliste Test');

$failures = [];
$passes = 0;

$reset = saas_send_password_reset_mail('mail-flow@test.local', str_repeat('a', 64));
mail_check_assert('password reset mail logs successfully', $reset['ok'] === true, $failures, $passes);
mail_check_assert('password reset mail file exists', isset($reset['path']) && is_file($reset['path']), $failures, $passes);
if (isset($reset['path']) && is_file($reset['path'])) {
    $content = file_get_contents($reset['path']) ?: '';
    mail_check_assert('password reset mail contains app url', str_contains($content, 'https://app.example.test/passwort-zuruecksetzen.php?token='), $failures, $passes);
}

$verification = saas_send_email_verification_mail('mail-flow@test.local', str_repeat('b', 64));
mail_check_assert('email verification mail logs successfully', $verification['ok'] === true, $failures, $passes);
mail_check_assert('email verification mail file exists', isset($verification['path']) && is_file($verification['path']), $failures, $passes);
if (isset($verification['path']) && is_file($verification['path'])) {
    $content = file_get_contents($verification['path']) ?: '';
    mail_check_assert('email verification mail contains app url', str_contains($content, 'https://app.example.test/email-verifizieren.php?token='), $failures, $passes);
}

$invalid = saas_send_mail('not-an-email', 'Test', 'Body');
mail_check_assert('invalid recipient is rejected', $invalid['ok'] === false, $failures, $passes);

foreach (glob($logDir . '/*.txt') ?: [] as $file) {
    unlink($file);
}

if ($failures !== []) {
    echo "\nM3 mail flow check failed with " . count($failures) . " failure(s):\n";
    foreach ($failures as $failure) {
        echo "- {$failure}\n";
    }
    exit(1);
}

echo "\nM3 mail flow check passed with {$passes} assertions.\n";
