<?php

namespace MintyPHP\Module\Security\Service;

use MintyPHP\Service\Settings\SettingsMetadataGateway;

/**
 * Global presentation settings for the customer security-check report PDF.
 *
 * Stores the admin-authored HTML/CSS report template in the core `settings`
 * table (GR-CORE-011). The template is not a secret, so it is stored in clear
 * text (unlike the BC credentials in SecurityBcSettingsGateway). Setting keys
 * are prefixed with 'security.' to avoid cross-module collisions.
 *
 * The uploaded report logo is a binary asset and lives on the filesystem —
 * see SecurityReportLogoService — not here.
 *
 * @api Consumed by the Security report-design page and SecurityReportPdfService.
 */
class SecurityReportSettingsGateway
{
    public const KEY_TEMPLATE_HTML = 'security.report_template_html';

    /** Soft cap so the settings row stays sane; a real template is a few KB. */
    public const MAX_TEMPLATE_LENGTH = 200000;

    public function __construct(
        private readonly SettingsMetadataGateway $settingsMetadataGateway
    ) {
    }

    /**
     * The stored custom template, or '' when none is configured (the PDF service
     * then falls back to its built-in default layout).
     */
    public function getTemplateHtml(): string
    {
        return trim((string) ($this->settingsMetadataGateway->getValue(self::KEY_TEMPLATE_HTML) ?? ''));
    }

    public function hasCustomTemplate(): bool
    {
        return $this->getTemplateHtml() !== '';
    }

    /**
     * Persist the template. Passing null or an empty/blank string clears it,
     * restoring the built-in default. Returns false if the value exceeds the
     * soft length cap.
     */
    public function setTemplateHtml(?string $html): bool
    {
        $html = trim((string) ($html ?? ''));
        if ($html !== '' && strlen($html) > self::MAX_TEMPLATE_LENGTH) {
            return false;
        }

        return $this->settingsMetadataGateway->set(
            self::KEY_TEMPLATE_HTML,
            $html !== '' ? $html : null,
            self::KEY_TEMPLATE_HTML
        );
    }
}
