<?php

namespace App\Http\Controllers;

use App\Http\Requests\GetIntegrationTokenRequest;
use App\IntegrationRepository;
use Illuminate\Http\JsonResponse;

class IntegrationController extends Controller
{
    public function getToken(GetIntegrationTokenRequest $request, IntegrationRepository $repository): JsonResponse
    {
        $integration = $repository->getEnabledIntegration($request->input('integration'));

        if (!$repository->supportsToken($integration)) {
            return response()->json([
                'error' => 'Integration does not support token or is disabled.'
            ], 400);
        }

        try {
            $service = app($integration['class']);
            $token = $service->getToken();
            return response()->json([
                'access_token' => $token
            ]);
        } catch (\Throwable $e) {
            return response()->json([
                'error' => $e->getMessage()
            ], 500);
        }
    }
}
