<?php
declare(strict_types=1);

class LdapPlugin
{
    public function register(): void
    {
        require_once __DIR__ . '/LdapAuthAdapter.php';
        require_once __DIR__ . '/LdapProvisioner.php';
        require_once __DIR__ . '/LdapSync.php';
        require_once __DIR__ . '/LdapAdminController.php';

        // ── Routes ───────────────────────────────────────────────────────────
        PluginManager::addRoute('/admin/plugins/ldap', fn() => LdapAdminController::index());

        // ── Auth filter ──────────────────────────────────────────────────────
        // Returns null for "not my user, fall through to local password check",
        // returns an array for "user authenticated, use this row".
        PluginManager::addFilter('auth_external_login', function ($_, array $ctx): ?array {
            if (!extension_loaded('ldap')) return null;
            if (Helper::getSetting('ldap_enabled', '0') !== '1') return null;

            return LdapAuthAdapter::tryAuthenticate(
                (string)($ctx['email'] ?? ''),
                (string)($ctx['password'] ?? ''),
                $ctx['user'] ?? null
            );
        });

        // ── Cron tick ────────────────────────────────────────────────────────
        // Throttled inside the sync class so the plugin can be hooked into a
        // generic cron_tick without flooding the directory on every minute.
        PluginManager::on('cron_tick', function (mixed $ctx): void {
            if (Helper::getSetting('ldap_enabled', '0') !== '1') return;
            LdapSync::runIfDue();
        });
    }
}
