<?php

use MintyPHP\Http\ApiAuth;
use MintyPHP\Http\ApiBootstrap;
use MintyPHP\Http\ApiResponse;
use MintyPHP\Repository\Tenant\TenantRepository;
use MintyPHP\Service\Auth\AuthServicesFactory;

ApiBootstrap::init();
ApiResponse::requireMethod('POST');
$apiTokenService = (new AuthServicesFactory())->createApiTokenService();

$userId = ApiAuth::userId();
if ($userId <= 0) {
    ApiResponse::unauthorized();
}

ApiAuth::requireSelfManageTokens();

$scopedTenantId = ApiAuth::scopedTenantId();
$scopedTenantUuid = null;
if ($scopedTenantId !== null && $scopedTenantId > 0) {
    $tenant = (new TenantRepository())->find($scopedTenantId);
    $scopedTenantUuid = trim((string) ($tenant['uuid'] ?? ''));
    if ($scopedTenantUuid === '') {
        $scopedTenantUuid = null;
    }
}
$result = $apiTokenService->revokeAllForUser($userId, $scopedTenantId);

ApiResponse::success([
    'data' => [
        'revoked_count' => (int) ($result['count'] ?? 0),
        'tenant_uuid' => $scopedTenantUuid,
    ],
]);
