<?php
/**
 * 2026 Paysera
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Academic Free License (AFL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://opensource.org/licenses/afl-3.0.php
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@prestashop.com so we can send you a copy immediately.
 *
 * @author Paysera <plugins@paysera.com>
 * @copyright 2026 Paysera
 * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
 * International Registered Trademark & Property of Paysera
 */

declare(strict_types=1);

namespace Paysera\PrestashopPayments\Diagnostic\Service\Formatter;

use Paysera\PrestashopPayments\Diagnostic\Dto\CheckResult;
use Paysera\PrestashopPayments\Diagnostic\Dto\DiagnosticSection;

if (!defined('_PS_VERSION_')) {
    exit;
}

class TableFormatter
{
    private const RULE_WIDTH = 72;
    private const CONTINUATION_INDENT = '  ';

    /**
     * @param array<string, DiagnosticSection> $sections
     */
    public function format(array $sections): string
    {
        $output = 'PAYSERA PRESTASHOP PLUGIN - DIAGNOSTIC REPORT' . PHP_EOL;
        $output .= 'Generated: ' . gmdate('Y-m-d H:i:s') . PHP_EOL;
        $output .= str_repeat('=', self::RULE_WIDTH) . PHP_EOL;

        $isFirstSection = true;
        foreach ($sections as $section) {
            if (!$isFirstSection) {
                $output .= PHP_EOL;
            }
            $output .= $this->formatSection($section);
            $isFirstSection = false;
        }

        return $output;
    }

    private function formatSection(DiagnosticSection $section): string
    {
        $output = strtoupper($section->getLabel()) . PHP_EOL;
        $output .= str_repeat('=', self::RULE_WIDTH) . PHP_EOL;

        foreach ($section->getResults() as $result) {
            $output .= $this->formatResult($result);
        }

        return $output;
    }

    private function formatResult(CheckResult $result): string
    {
        $status = $result->isSuccessful() ? 'Pass' : 'Fail';
        $lines = explode("\n", $result->getDetails());
        $firstLine = array_shift($lines);

        $output = sprintf('%s: %s - %s', $result->getName(), $status, $firstLine) . PHP_EOL;
        foreach ($lines as $line) {
            $output .= self::CONTINUATION_INDENT . $line . PHP_EOL;
        }

        return $output;
    }
}
