<?php

declare(strict_types=1);

namespace App\Support\Inventory;

class InventoryPolicyTypeMeta
{
    /**
     * Canonical inventory policy-type metadata source-of-truth.
     *
     * These definitions are used for UI classification (restore/risk) and KPI aggregation.
     * The authoritative inputs are:
     * - `inventory_items.policy_type`
     * - `config('tenantpilot.supported_policy_types')` and `config('tenantpilot.foundation_types')`
     *   meta fields, especially: `restore`, `risk`.
     */
    public static function all(): array
    {
        return array_merge(
            static::supported(),
            static::foundations(),
        );
    }

    /**
     * @return array<int, array<string, mixed>>
     */
    public static function supported(): array
    {
        $supported = config('tenantpilot.supported_policy_types', []);

        return is_array($supported) ? $supported : [];
    }

    /**
     * @return array<int, array<string, mixed>>
     */
    public static function foundations(): array
    {
        $foundations = config('tenantpilot.foundation_types', []);

        return is_array($foundations) ? $foundations : [];
    }

    /**
     * @return array<string, array<string, mixed>>
     */
    public static function byType(): array
    {
        return collect(static::all())
            ->filter(fn (array $row): bool => filled($row['type'] ?? null))
            ->keyBy(fn (array $row): string => (string) $row['type'])
            ->all();
    }

    /**
     * @return array<string, mixed>
     */
    public static function metaFor(?string $type): array
    {
        if (! filled($type)) {
            return [];
        }

        return static::byType()[(string) $type] ?? [];
    }

    public static function restoreMode(?string $type): ?string
    {
        $restore = static::metaFor($type)['restore'] ?? null;

        return is_string($restore) ? $restore : null;
    }

    public static function riskLevel(?string $type): ?string
    {
        $risk = static::metaFor($type)['risk'] ?? null;

        return is_string($risk) ? $risk : null;
    }

    public static function isRestorable(?string $type): bool
    {
        return static::restoreMode($type) === 'enabled';
    }

    public static function isPartial(?string $type): bool
    {
        $restore = static::restoreMode($type);

        return filled($restore) && $restore !== 'enabled';
    }

    public static function isHighRisk(?string $type): bool
    {
        $risk = static::riskLevel($type);

        return is_string($risk) && str_contains($risk, 'high');
    }
}
