<?php

namespace App\Http\Controllers;

use App\Modules\VehiclesInVideo\Services\TokenService;
use Illuminate\Http\JsonResponse;

class VehiclesInVideoController extends Controller
{
    public function __construct(
        private readonly TokenService $tokenService,
    ) {
    }

    public function token(): JsonResponse
    {
        $token = $this->tokenService->latestToken();

        return response()->json([
            'token' => $token ? [
                'id' => $token->id,
                'connected' => $token->isConnected(),
                'grant_url' => $token->grant_url,
                'refresh_expires_at' => $token->refresh_expires_at,
            ] : null,
        ]);
    }

    public function requestGrantUrl(): JsonResponse
    {
        $result = $this->tokenService->requestGrantUrl();

        return response()->json($result, $result['success'] ? 200 : 422);
    }

    public function refreshToken(): JsonResponse
    {
        $result = $this->tokenService->refreshToken();

        return response()->json($result, $result['success'] ? 200 : 422);
    }

    public function deleteTokens(): JsonResponse
    {
        $result = $this->tokenService->deleteAllTokens();

        return response()->json($result, $result['success'] ? 200 : 422);
    }
}
