#!/usr/bin/env php
<?php

/**
 * Synchronizes module-declared permissions into the permissions table.
 *
 * Usage: php bin/module-permissions-sync.php
 *
 * Exit codes:
 *   0 — sync successful
 *   1 — error during sync
 */

declare(strict_types=1);

use MintyPHP\App\Module\ModulePermissionSynchronizer;
use MintyPHP\App\Module\ModuleRegistry;
use MintyPHP\Repository\Access\PermissionRepository;

require_once __DIR__ . '/module-cli-bootstrap.php';

function modulePermissionsSyncRun(): int
{
    return moduleCliRunStep('module-permissions-sync', static function (): int {
        $lockFile = __DIR__ . '/../storage/runtime/.module-permissions-sync.lock';

        return moduleCliWithFileLock(
            $lockFile,
            'module-permissions-sync: another sync is in progress, skipping.',
            static function (): int {
                $synchronizer = new ModulePermissionSynchronizer(
                    app(ModuleRegistry::class),
                    app(PermissionRepository::class)
                );
                $result = $synchronizer->sync();

                fwrite(STDOUT, sprintf(
                    "module-permissions-sync: created=%d updated=%d unchanged=%d total=%d\n",
                    $result['created'],
                    $result['updated'],
                    $result['unchanged'],
                    $result['total']
                ));

                return 0;
            }
        );
    });
}

if (PHP_SAPI === 'cli' && realpath((string) ($_SERVER['SCRIPT_FILENAME'] ?? '')) === __FILE__) {
    exit(modulePermissionsSyncRun());
}
