<?php

use MintyPHP\Http\ApiAuth;
use MintyPHP\Http\ApiBootstrap;
use MintyPHP\Http\ApiResponse;
use MintyPHP\Service\Auth\ApiTokenEndpointService;

ApiBootstrap::init();
$apiTokenEndpointService = app(ApiTokenEndpointService::class);
$request = requestInput();

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

ApiAuth::requireSelfManageTokens();

$tokenUuid = trim((string) ($id ?? ''));
$token = $apiTokenEndpointService->findSelfToken($tokenUuid, $userId, ApiAuth::scopedTenantId(), ApiAuth::tokenId());
if (!$token) {
    ApiResponse::notFound();
}

$method = $request->method();

if ($method === 'GET') {
    ApiResponse::success([
        'data' => [
            'uuid' => (string) ($token['uuid'] ?? ''),
            'name' => (string) ($token['name'] ?? ''),
            'selector_prefix' => substr((string) ($token['selector'] ?? ''), 0, 8),
            'tenant_uuid' => $token['tenant_uuid'] ?? null,
            'last_used_at' => $token['last_used_at'] ?? null,
            'last_ip' => (string) ($token['last_ip'] ?? ''),
            'expires_at' => $token['expires_at'] ?? null,
            'revoked_at' => $token['revoked_at'] ?? null,
            'created' => $token['created'] ?? null,
            'is_current_token' => (int) ($token['id'] ?? 0) === (int) (ApiAuth::tokenId() ?? 0),
        ],
    ]);
}

if ($method === 'DELETE') {
    $revoked = $apiTokenEndpointService->revokeSelfToken($tokenUuid, $userId);
    if (!$revoked) {
        ApiResponse::error('revoke_failed', 422);
    }
    ApiResponse::noContent();
}

ApiResponse::methodNotAllowed();
