<?php

declare(strict_types=1);

namespace ApiModel\Action;

use ApiModel\Service\PlatformService;
use ApiModel\Shared\Support\AuthContext;
use ApiModel\Shared\Http\HttpUtil;
use Psr\Http\Message\ServerRequestInterface;

final class PlatformAction
{
    public function __construct(private readonly PlatformService $platform) {}

    /** @return array<string, mixed> */
    public function listUsers(ServerRequestInterface $request): array
    {
        $u = AuthContext::jwtUser($request);
        AuthContext::requireRoles($u, ['PLATFORM_ADMIN']);
        $q = $request->getQueryParams();

        return $this->platform->listUsers(
            max(1, (int) ($q['page'] ?? 1)),
            min(100, max(1, (int) ($q['limit'] ?? 20))),
            $q['q'] ?? null,
        );
    }

    /** @return array<string, mixed> */
    public function createUser(ServerRequestInterface $request): array
    {
        $u = AuthContext::jwtUser($request);
        AuthContext::requireRoles($u, ['PLATFORM_ADMIN']);

        return $this->platform->createUser($u, HttpUtil::parseJson($request));
    }

    /** @return array<string, mixed> */
    public function updateUser(ServerRequestInterface $request, string $id): array
    {
        $u = AuthContext::jwtUser($request);
        AuthContext::requireRoles($u, ['PLATFORM_ADMIN']);

        return $this->platform->updateUser($u, $id, HttpUtil::parseJson($request));
    }

    /** @return array<string, mixed> */
    public function listAuditEvents(ServerRequestInterface $request): array
    {
        $u = AuthContext::jwtUser($request);
        AuthContext::requireRoles($u, ['PLATFORM_ADMIN']);
        $q = $request->getQueryParams();

        return $this->platform->listPlatformAudit(
            max(1, (int) ($q['page'] ?? 1)),
            min(100, max(1, (int) ($q['limit'] ?? 20))),
        );
    }
}
