<?php

namespace App\Http\Controllers\Api\V1;

use App\Domain\API\ApiCredentialService;
use App\Http\Controllers\Controller;
use App\Support\Security\TotpService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ApiTokenController extends Controller
{
    public function __construct(
        private readonly ApiCredentialService $credentialService,
        private readonly TotpService $totpService,
    ) {
    }

    public function rotate(Request $request): JsonResponse
    {
        $request->validate([
            'totp_code' => ['nullable', 'string', 'max:12'],
            'confirm' => ['required', 'boolean'],
        ]);

        if (! $request->boolean('confirm')) {
            return response()->json(['message' => 'Action not confirmed.'], 422);
        }

        if (! $this->totpService->verify($request->user(), $request->input('totp_code'))) {
            return response()->json(['message' => 'Invalid 2FA code.'], 422);
        }

        return response()->json($this->credentialService->rotate($request->user()));
    }
}
