<?php

declare(strict_types=1);

final class MyronJsonLdService
{
    public function __construct(
        private readonly MyronJsonLdGenerator $generator,
        private readonly MyronJsonLdEncoder $encoder,
    ) {
    }

    /**
     * @param array<string, mixed> $settings
     */
    public function renderGlobal(array $settings): string
    {
        if (empty($settings['seo_enable_json_ld_output'])) {
            return '';
        }
        return $this->renderSchemas($this->generator->globalSchemas($settings));
    }

    /**
     * @param array<string, mixed> $page
     * @param array<string, mixed> $settings
     */
    public function renderPage(array $page, array $settings): string
    {
        if (empty($settings['seo_enable_json_ld_output'])) {
            return '';
        }
        return $this->renderSchemas($this->generator->pageSchemas($page, $settings));
    }

    /**
     * @param list<array<string, mixed>|string> $schemas
     */
    private function renderSchemas(array $schemas): string
    {
        $html = [];
        foreach ($schemas as $schema) {
            if (is_string($schema)) {
                $html[] = $schema;
                continue;
            }
            $encoded = $this->encoder->safeEncode($schema);
            if ($encoded === false) {
                continue;
            }
            $html[] = '<script type="application/ld+json">' . $encoded . '</script>';
        }
        return implode("\n", $html);
    }
}
