<?php

namespace App\Support;

/**
 * “权限语言”映射层：
 * - 把 UI 可理解的词汇（查看/可管理/可审核/导出/特权）映射到系统真实运行时校验的 `prd.*` slug
 * - 以及进一步映射到运行时 action code（如 `integration.site.view`）
 *
 * 当前仅把 integration-sites 作为首个落地示例，其它页面建议按同样结构逐步接入。
 */
final class AdminPermissionLanguage
{
    private static function cfg(): array
    {
        $cfg = config('admin_permission_language');
        if (is_array($cfg)) {
            return $cfg;
        }

        // 若存在 config cache 且未刷新（新加配置文件未生效），config() 可能拿不到该 key。
        // 兜底 require 该 PHP 配置文件，避免 Registry 产出空 slug / 空 permission_codes。
        $path = base_path('config/admin_permission_language.php');
        if (is_string($path) && file_exists($path)) {
            /** @var mixed $loaded */
            $loaded = require $path;
            return is_array($loaded) ? $loaded : [];
        }

        return [];
    }

    private static function categories(): array
    {
        return self::cfg()['categories'] ?? [];
    }

    private static function pages(): array
    {
        return self::cfg()['pages'] ?? [];
    }

    public static function pageLabel(string $pageKey): string
    {
        $pages = self::pages();
        $page = $pages[$pageKey] ?? null;
        $label = $page['label'] ?? '';
        return is_string($label) ? $label : '';
    }

    public static function bundleCategoryKey(string $pageKey, string $bundleKey): string
    {
        $pages = self::pages();
        $page = $pages[$pageKey] ?? [];
        $bundle = $page['bundles'][$bundleKey] ?? [];
        $category = is_array($bundle) ? ($bundle['category'] ?? '') : '';
        return is_string($category) ? $category : '';
    }

    public static function bundleLabel(string $pageKey, string $bundleKey): string
    {
        $categoryKey = self::bundleCategoryKey($pageKey, $bundleKey);
        $categories = self::categories();
        $category = $categories[$categoryKey] ?? null;
        $label = $category['label'] ?? '';
        return is_string($label) ? $label : '';
    }

    public static function prdSlug(string $pageKey, string $bundleKey): string
    {
        $pages = self::pages();
        $page = $pages[$pageKey] ?? [];
        $bundle = $page['bundles'][$bundleKey] ?? [];
        $slug = is_array($bundle) ? ($bundle['prd_slug'] ?? '') : '';
        return is_string($slug) ? $slug : '';
    }

    /** @return list<string> */
    public static function permissionCodes(string $pageKey, string $bundleKey): array
    {
        $pages = self::pages();
        $page = $pages[$pageKey] ?? [];
        $bundle = $page['bundles'][$bundleKey] ?? [];
        $codes = is_array($bundle) ? ($bundle['permission_codes'] ?? []) : [];

        return is_array($codes) ? array_values(array_filter($codes, static fn ($v): bool => is_string($v) && $v !== '')) : [];
    }

    public static function prdName(string $pageKey, string $bundleKey): string
    {
        return sprintf('%s·%s', self::pageLabel($pageKey), self::bundleLabel($pageKey, $bundleKey));
    }

    /** @return list<string> */
    public static function requiredBundleKeys(string $pageKey): array
    {
        $pages = self::pages();
        $page = $pages[$pageKey] ?? [];
        $required = $page['required_bundles'] ?? [];
        if (! is_array($required)) {
            return [];
        }

        return array_values(array_filter($required, static fn ($v): bool => is_string($v) && $v !== ''));
    }

    /** @return list<string> */
    public static function requiredAnyPrdSlugs(string $pageKey): array
    {
        $bundleKeys = self::requiredBundleKeys($pageKey);
        if ($bundleKeys === []) {
            return [];
        }

        $slugs = [];
        foreach ($bundleKeys as $bundleKey) {
            $slug = self::prdSlug($pageKey, $bundleKey);
            if (is_string($slug) && $slug !== '') {
                $slugs[] = $slug;
            }
        }

        return array_values(array_unique($slugs));
    }
}

