<?php

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

ApiBootstrap::init();
ApiResponse::requireMethod('POST');
$apiTokenService = (app(AuthServicesFactory::class))->createApiTokenService();
$apiTokenEndpointService = app(ApiTokenEndpointService::class);
$request = requestInput();

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

ApiAuth::requireSelfManageTokens();

$currentTokenId = (int) (ApiAuth::tokenId() ?? 0);
if ($currentTokenId <= 0) {
    ApiResponse::error('current_token_not_found', 404);
}

$input = $request->bodyAll();
$expiresInput = trim((string) ($input['expires_at'] ?? ''));
$expiresAt = $expiresInput !== '' ? $expiresInput : null;

$result = $apiTokenService->rotateCurrentToken($userId, $currentTokenId, $expiresAt);
if (!($result['ok'] ?? false)) {
    $error = (string) ($result['error'] ?? 'rotate_failed');
    if ($error === 'current_token_not_found') {
        ApiResponse::error($error, 404);
    }
    if ($error === 'max_tokens_reached') {
        ApiResponse::error($error, 409);
    }
    if ($error === 'invalid_expires_at' || $error === 'current_token_invalid') {
        ApiResponse::error($error, 422);
    }
    ApiResponse::error('rotate_failed', 422);
}

$tenantUuid = null;
$tenantId = isset($result['tenant_id']) ? (int) ($result['tenant_id']) : 0;
if ($tenantId > 0) {
    $tenantUuid = $apiTokenEndpointService->resolveTenantUuidById($tenantId);
}

ApiResponse::success([
    'data' => [
        'token' => (string) ($result['token'] ?? ''),
        'token_uuid' => (string) ($result['uuid'] ?? ''),
        'selector_prefix' => substr((string) ($result['selector'] ?? ''), 0, 8),
        'tenant_uuid' => $tenantUuid,
        'expires_at' => $result['expires_at'] ?? null,
    ],
], 201);
