<?php

namespace MintyPHP\Service\Settings;

class ThemeConfigGateway
{
    private const DEFAULT_THEMES = [
        'light' => 'Light',
        'dark' => 'Dark',
    ];

    private ?array $themes = null;

    public function all(): array
    {
        if ($this->themes !== null) {
            return $this->themes;
        }

        $file = dirname(__DIR__, 3) . '/config/themes.php';
        if (!is_file($file)) {
            $this->themes = self::DEFAULT_THEMES;
            return $this->themes;
        }

        $loaded = include $file;
        if (!is_array($loaded)) {
            $this->themes = self::DEFAULT_THEMES;
            return $this->themes;
        }

        $clean = [];
        foreach ($loaded as $key => $label) {
            $themeKey = strtolower(trim((string) $key));
            $themeLabel = trim((string) $label);
            if ($themeKey === '' || $themeLabel === '') {
                continue;
            }
            $clean[$themeKey] = $themeLabel;
        }

        // Fall back to defaults if the file returns an empty or invalid list — system must always have themes.
        $this->themes = $clean ?: self::DEFAULT_THEMES;
        return $this->themes;
    }
}
