<?php

namespace App\Support;

final class AdminPermissionInheritance
{
    /**
     * @var array<string, list<string>>
     */
    private const IMPLIED_BY_SLUG = [
        'prd.agent.manage' => ['prd.agent.view'],
        'prd.agent.role.manage' => ['prd.agent.role.view', 'prd.agent.view'],
        'prd.agent.user.manage' => ['prd.agent.user.view', 'prd.agent.view'],
        'prd.integration.manage' => ['prd.integration.view'],
        'prd.wallet_reconcile.manage' => ['prd.wallet_reconcile.view'],
        'prd.draw_result.manage' => ['prd.draw_result.view'],
        'prd.odds.manage' => ['prd.odds.view'],
        'prd.risk_cap.manage' => ['prd.risk_cap.view'],
        'prd.rebate.manage' => ['prd.rebate.view'],
        'prd.jackpot.manage' => ['prd.jackpot.view'],
        'prd.payout.manage' => ['prd.payout.view'],
        'prd.payout.review' => ['prd.payout.view'],
        'prd.report.export' => ['prd.report.view'],
        'prd.risk.manage' => ['prd.risk.view'],
    ];

    /**
     * @param  list<string>  $permissionSlugs
     * @return list<string>
     */
    public static function expand(array $permissionSlugs): array
    {
        $expanded = [];

        foreach ($permissionSlugs as $slug) {
            if (! is_string($slug) || $slug === '') {
                continue;
            }

            self::appendWithImplications($expanded, $slug);
        }

        return array_values(array_keys($expanded));
    }

    /**
     * @param  array<string, true>  $accumulator
     */
    private static function appendWithImplications(array &$accumulator, string $slug): void
    {
        if (isset($accumulator[$slug])) {
            return;
        }

        $accumulator[$slug] = true;

        foreach (self::IMPLIED_BY_SLUG[$slug] ?? [] as $implied) {
            self::appendWithImplications($accumulator, $implied);
        }
    }
}
