<?php

declare(strict_types=1);

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

use FecaMailshots\Application\TemplateRenderer;

$pngBytes = base64_decode(
    'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQAAAAA3bvkkAAAAIGNIUk0AAHomAACAhAAA+gAAAIDoAAB1MAAA6mAAADqYAAAXcJy6UTwAAAACYktHRAAB3YoTpAAAAAd0SU1FB+oEGAYzAgXOM1oAAAAKSURBVAjXY2gAAACCAIHdQ2r0AAAAJXRFWHRkYXRlOmNyZWF0ZQAyMDI2LTA0LTI0VDA2OjUxOjAyKzAwOjAwPufkWAAAACV0RVh0ZGF0ZTptb2RpZnkAMjAyNi0wNC0yNFQwNjo1MTowMiswMDowME+6XOQAAAAodEVYdGRhdGU6dGltZXN0YW1wADIwMjYtMDQtMjRUMDY6NTE6MDIrMDA6MDAYr307AAAAAElFTkSuQmCC',
    true
);
if (!is_string($pngBytes) || $pngBytes === '') {
    fwrite(STDERR, "Failed to decode png fixture bytes\n");
    exit(1);
}

$renderer = new TemplateRenderer(
    static function (string $name) use ($pngBytes): ?array {
        if (strtolower(trim($name)) !== 'logo_asset') {
            return null;
        }
        return [
            'name' => 'logo_asset',
            'file_name' => 'logo.png',
            'mime_type' => 'image/png',
            'file_bytes' => $pngBytes,
            'width_mm' => 20,
            'height_mm' => 10,
            'justification' => 'left',
        ];
    }
);

$rendered = $renderer->render(
    'Subject',
    '<p>Body</p>',
    '<div>{{ pdf_asset("logo_asset") }}</div>',
    []
);

$pdfHtml = (string) ($rendered['pdf_attachment'] ?? '');
if (strpos($pdfHtml, 'data:image/png;base64,') === false && strpos($pdfHtml, 'data:image/jpeg;base64,') === false) {
    fwrite(STDERR, "pdf_asset did not render png/jpeg data-uri image HTML\n");
    exit(1);
}
if (strpos($pdfHtml, 'text-align:left') === false) {
    fwrite(STDERR, "pdf_asset did not apply left justification wrapper\n");
    exit(1);
}
if (strpos($pdfHtml, 'width:20mm;height:10mm;') === false) {
    fwrite(STDERR, "pdf_asset did not apply width/height mm styles\n");
    exit(1);
}

try {
    $renderer->render('S', 'M', '{{ pdf_asset("missing_asset") }}', []);
    fwrite(STDERR, "Expected hard error for missing pdf_asset, but render succeeded\n");
    exit(1);
} catch (Throwable $e) {
    if (strpos($e->getMessage(), 'not found') === false) {
        fwrite(STDERR, "Unexpected missing-asset error message: {$e->getMessage()}\n");
        exit(1);
    }
}

echo "TemplateRenderer pdf_asset regression test passed\n";
