<?php

namespace routes;

use classes\superuser_system_status_service;
use traits\route_t;

class superuserSystemStatusRoute
{
    use route_t;

    public function run(): void
    {
        $this->get('/superuser/system/status', function () {
            global $response;

            $this->requirePermission('superuser_system_status_view');
            $force = $this->toBool($this->getParameter('force'), false);
            $snapshot = (new superuser_system_status_service())->getSnapshot($force);
            $response->success($snapshot);
        }, [
            'superuser_system_status_view' => 'View the aggregated superuser system status snapshot',
        ]);

        $this->get('/superuser/system/database/status', function () {
            global $response;

            $this->requirePermission('superuser_system_status_view');
            $snapshot = (new superuser_system_status_service())->getSnapshot(false);
            $response->success([
                'status' => $snapshot['dependencies']['database'] ?? null,
            ]);
        }, [
            'superuser_system_status_view' => 'View the aggregated superuser system status snapshot',
        ]);
    }

    private function toBool(mixed $value, bool $default): bool
    {
        if (is_bool($value)) {
            return $value;
        }

        if ($value === null) {
            return $default;
        }

        $normalized = strtolower(trim((string)$value));
        if (in_array($normalized, ['1', 'true', 'yes', 'on'], true)) {
            return true;
        }
        if (in_array($normalized, ['0', 'false', 'no', 'off'], true)) {
            return false;
        }

        return $default;
    }
}
