<?php

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

ApiBootstrap::init();
$apiTokenRepository = new ApiTokenRepository();

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

ApiAuth::requireSelfManageTokens();

$tokenUuid = trim((string) ($id ?? ''));
if (!$apiTokenRepository->isUuid($tokenUuid)) {
    ApiResponse::notFound();
}

$token = $apiTokenRepository->findByUuidForUser($tokenUuid, $userId);
if (!$token) {
    ApiResponse::notFound();
}

$scopedTenantId = ApiAuth::scopedTenantId();
$tokenTenantId = isset($token['tenant_id']) ? (int) $token['tenant_id'] : null;
if ($tokenTenantId !== null && $tokenTenantId <= 0) {
    $tokenTenantId = null;
}
if ($scopedTenantId !== null && $scopedTenantId > 0 && $tokenTenantId !== $scopedTenantId) {
    ApiResponse::notFound();
}
$tenantUuid = null;
if ($tokenTenantId !== null) {
    $tenant = (new TenantRepository())->find($tokenTenantId);
    $tenantUuid = trim((string) ($tenant['uuid'] ?? ''));
    if ($tenantUuid === '') {
        $tenantUuid = null;
    }
}

$method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');

if ($method === 'GET') {
    ApiResponse::success([
        'data' => [
            'uuid' => (string) ($token['uuid'] ?? ''),
            'name' => (string) ($token['name'] ?? ''),
            'selector_prefix' => substr((string) ($token['selector'] ?? ''), 0, 8),
            'tenant_uuid' => $tenantUuid,
            '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 = $apiTokenRepository->revokeByUuidForUser($tokenUuid, $userId);
    if (!$revoked) {
        ApiResponse::error('revoke_failed', 422);
    }
    ApiResponse::noContent();
}

ApiResponse::methodNotAllowed();
