<?php

namespace App\Services;

use App\DTOs\CatalogPageData;
use App\DTOs\CatalogRenderedPage;
use App\Enums\LandingPageVersion;
use RuntimeException;

class CatalogTemplateRenderer
{
    public function __construct(private CatalogTemplateLocator $locator) {}

    public function render(LandingPageVersion $version, CatalogPageData $catalog, string $template): CatalogRenderedPage
    {
        $data = $catalog->toArray();
        $directory = $this->locator->directory($version, $template);
        $phtml = $directory.DIRECTORY_SEPARATOR.'index.phtml';

        if (! is_file($phtml)) {
            throw new RuntimeException(
                "Add index.phtml to resources/landing-page-templates/{$version->value}/{$template}",
            );
        }

        $html = $this->includePhtml($phtml, $data);
        $cssPath = $directory.DIRECTORY_SEPARATOR.'style.css';
        $jsPath = $directory.DIRECTORY_SEPARATOR.'script.js';

        return new CatalogRenderedPage(
            title: $catalog->heroTitle !== '' ? $catalog->heroTitle : $version->label(),
            html: $html,
            css: is_file($cssPath) ? (string) file_get_contents($cssPath) : '',
            js: is_file($jsPath) ? (string) file_get_contents($jsPath) : '',
            prompt: "Wired catalog JSON into landing-page-templates/{$version->value}/{$template}/index.phtml\n".json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE),
        );
    }

    /**
     * @param  array<string, mixed>  $data
     */
    private function includePhtml(string $path, array $data): string
    {
        $render = static function (string $path, array $data): void {
            include $path;
        };

        ob_start();
        $render($path, $data);

        return trim((string) ob_get_clean());
    }
}
