<?php

declare(strict_types=1);

require_once dirname(__DIR__, 2) . '/feca_mailshots_plugin/src/autoload.php';

use FecaMailshots\Infrastructure\BasicSmtpSender;

$sender = new BasicSmtpSender();
$ref = new ReflectionClass($sender);
$buildMime = $ref->getMethod('buildMime');
$buildMime->setAccessible(true);

$plain = $buildMime->invoke(
    $sender,
    'from@example.org',
    'From Name',
    ['to@example.org'],
    [],
    [],
    "All Saint's café",
    '<p>Hello</p>',
    null,
    []
);

if (!is_string($plain) || strpos($plain, 'Content-Type: text/html; charset=UTF-8') === false) {
    fwrite(STDERR, "Plain MIME rendering missing HTML content-type header\n");
    exit(1);
}
if (strpos($plain, "Subject: All Saint's café") !== false) {
    fwrite(STDERR, "Subject header should not contain raw UTF-8/punctuation text\n");
    exit(1);
}
if (strpos($plain, 'Subject: =?UTF-8?B?QWxsIFNhaW50J3MgY2Fmw6k=?=') === false) {
    fwrite(STDERR, "Subject header missing expected RFC 2047 encoding\n");
    exit(1);
}
if (strpos($plain, 'From: =?UTF-8?B?RnJvbSBOYW1l?= <from@example.org>') === false) {
    fwrite(STDERR, "From display name missing expected RFC 2047 encoding\n");
    exit(1);
}

$bytes = random_bytes(256 * 1024);
$mime = $buildMime->invoke(
    $sender,
    'from@example.org',
    'From Name',
    ['to@example.org'],
    [],
    [],
    'Subject',
    '<p>Hello</p>',
    null,
    [[
        'filename' => 'sample.jpg',
        'mime_type' => 'image/jpeg',
        'content_bytes' => $bytes,
    ]]
);

if (!is_string($mime) || strpos($mime, 'multipart/mixed') === false) {
    fwrite(STDERR, "Multipart MIME expected for attachment payload\n");
    exit(1);
}
if (strpos($mime, 'Content-Type: image/jpeg; name="sample.jpg"') === false) {
    fwrite(STDERR, "Attachment MIME part missing expected content-type/filename\n");
    exit(1);
}
if (strpos($mime, base64_encode(substr($bytes, 0, 24))) === false) {
    fwrite(STDERR, "Attachment bytes do not appear to be base64-encoded into MIME payload\n");
    exit(1);
}

echo "BasicSmtpSender MIME regression test passed\n";
