<?php

namespace App\Services\Enterprise;

use App\Core\Database;
use PDO;

final class EnterpriseRbacSynchronizer
{
    public static function report(): array
    {
        $db = Database::getInstance();

        $registry = EnterpriseRegistry::enabled();

        $report = [];

        foreach ($registry as $module) {

            $stmt = $db->prepare("
                SELECT *
                FROM rbac_menu_items
                WHERE menu_key = ?
                LIMIT 1
            ");

            $stmt->execute([
                $module['key']
            ]);

            $menu = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$menu) {

                $report[] = [

                    'module' =>
                        $module['key'],

                    'status' =>
                        'missing_menu',

                    'message' =>
                        'RBAC menu does not exist.'

                ];

                continue;
            }

            $issues = [];

            if (($menu['url'] ?? '') !== $module['route']) {

                $issues[] = 'URL mismatch';

            }

            if (($menu['icon'] ?? '') !== $module['icon']) {

                $issues[] = 'Icon mismatch';

            }

            if (($menu['i18n_key'] ?? '') !== $module['label_key']) {

                $issues[] = 'Translation key mismatch';

            }

            $report[] = [

                'module' =>
                    $module['key'],

                'status' =>
                    empty($issues)
                        ? 'healthy'
                        : 'warning',

                'message' =>
                    empty($issues)
                        ? 'RBAC synchronized'
                        : implode(', ', $issues)

            ];

        }

        return $report;
    }
}
