<?php

use Acms\Services\Setup\Fix\Tools\Access;
use Acms\Services\Setup\Fix\Tools\Domain;
use Acms\Services\Setup\Fix\Tools\TfaReset;
use Acms\Services\Setup\Http\Middleware\AuthMiddleware;
use Acms\Services\Setup\Http\Middleware\CsrfMiddleware;
use Acms\Services\Setup\Http\Middleware\SessionMiddleware;
use Acms\Services\Setup\Http\Pipeline;
use Acms\Services\Setup\Http\Request;
use Acms\Services\Setup\Http\Response;
use Acms\Services\Setup\SetupSession;
use Acms\Services\Setup\Tool\ToolRunner;

require_once(dirname(__FILE__) . '/application.php');

// メンテナンス（復旧）ツールのホワイトリスト（?c= の値 → Action）。
// ログイン不能時の復旧に限定（domain / access / 2FA リセット）。データ保守系の
// 修正ツールは管理画面のデータ修正メニューへ移設済み。描画は各 Action が持つ
// setup 専用 Twig（@setup/fix/{c}.twig）で行う。
$tools = [
    'domain' => Domain::class,
    'access' => Access::class,
    'tfa-reset' => TfaReset::class,
];

$command = isset($_GET['c']) ? (string)$_GET['c'] : '';
if (!isset($tools[$command])) {
    Response::html('<p>不正な命令です</p>')->emit();
    return;
}

// 認証必須の復旧ツール。全 submit を CSRF 検証（W2）する。
$session = new SetupSession();
$controller = $tools[$command];
$pipeline = new Pipeline(
    [
        new SessionMiddleware($session),
        new AuthMiddleware($session),
        new CsrfMiddleware($session, static fn(Request $req): bool => $req->isSubmitted()),
    ],
    new ToolRunner(new $controller(), $session)
);
$pipeline->handle(Request::fromGlobals())->emit();

App::checkException();
