<?php

namespace middlewares;

class SetupGuard implements BaseRequestMiddleware
{
    public static function handle($request): void
    {
        $cfSetup = new \CfSetup(\CfSettings::getInstance()->getConnection());
        $resource = $request->loadResource();
        $isSetupComplete = $cfSetup->isSetupComplete();

        // If setup is complete, Setup resources should not be allowed
        if ($isSetupComplete && $resource instanceof \Setup) {
            throw new \ResponseException(
                'Setup related operations are not allowed after setup completion.',
                \Response::FORBIDDEN
            );
        }

        // If setup is not complete, only Setup and SetupStatus resources are allowed
        if (
            !$isSetupComplete
            && !$resource instanceof \Setup
            && !$resource instanceof \SetupStatus
        ) {
            throw new \ResponseException(
                'This operation is not allowed until the setup is completed.',
                \Response::FORBIDDEN
            );
        }
    }
}
