<?php

declare(strict_types=1);

namespace Maestro\Core\Support;

use Illuminate\Support\Facades\Storage;
use Maestro\Core\Models\MaestroAppSetting;

final class MaestroAppSettingsPresenter
{
    /**
     * Logo URLs when using shipped defaults are omitted (null): the SPA uses bundled assets.
     * Non-null values are overrides stored on the public disk.
     *
     * @return array{
     *   theme: array<string, mixed>|null,
     *   logos: array<string, string|null>,
     *   maestroCore: array{npm: string|null, composer: string|null}
     * }
     */
    public static function toArray(?MaestroAppSetting $row = null): array
    {
        $row ??= MaestroAppSetting::instance();

        return [
            'theme' => $row->theme,
            'logos' => [
                'sidebar' => self::storagePublicUrlOrNull($row->logo_sidebar_path),
                'header' => self::storagePublicUrlOrNull($row->logo_header_path),
                'compact' => self::storagePublicUrlOrNull($row->logo_compact_path),
                'favicon' => self::storagePublicUrlOrNull($row->favicon_path),
                'loginHero' => self::storagePublicUrlOrNull($row->login_hero_path),
            ],
            'offerDocumentBackgrounds' => self::offerDocumentBackgroundEntries($row),
            'maestroCore' => MaestroCoreVersions::toArray(),
        ];
    }

    private static function storagePublicUrlOrNull(?string $storageRelativePath): ?string
    {
        if ($storageRelativePath === null || $storageRelativePath === '') {
            return null;
        }

        return Storage::disk('public')->url($storageRelativePath);
    }

    /**
     * @return list<array{path: string, url: string}>
     */
    private static function offerDocumentBackgroundEntries(MaestroAppSetting $row): array
    {
        $paths = $row->offer_document_background_paths ?? [];
        if (! is_array($paths)) {
            return [];
        }

        $out = [];
        foreach ($paths as $path) {
            if (! is_string($path) || $path === '') {
                continue;
            }
            $out[] = [
                'path' => $path,
                'url' => Storage::disk('public')->url($path),
            ];
        }

        return $out;
    }
}
