<?php

namespace App\Domains\Integration\Controllers;

use App\Domains\Client\Models\Client;
use App\Domains\Integration\Models\Integration;
use App\Domains\Integration\Requests\StoreClientIntegrationRequest;
use App\Domains\Integration\Services\ClientIntegrationService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;

class ClientIntegrationController extends Controller
{
    public function __construct(
        private readonly ClientIntegrationService $clientIntegrationService,
    ) {}

    public function index(Client $client): JsonResponse
    {
        return response()->json($this->clientIntegrationService->getAllForClient($client));
    }

    public function show(Client $client, string $integrationCode): JsonResponse
    {
        $integration = $this->clientIntegrationService->getClientIntegration($client, $integrationCode);

        if (! $integration) {
            return response()->json([
                'code' => 'integration.not_configured',
                'message' => __('api.integration.not_configured'),
            ], 404);
        }

        return response()->json($integration);
    }

    public function store(
        StoreClientIntegrationRequest $request,
        Client $client,
        string $integrationCode,
    ): JsonResponse {
        $integration = Integration::query()
            ->where('integration_code', $integrationCode)
            ->firstOrFail();

        try {
            $this->clientIntegrationService->updateOrCreateIntegration(
                $client,
                $integration,
                $request->input('integration_data', []),
            );

            return response()->json([
                'code' => 'integration.configured',
                'message' => __('api.integration.configured'),
            ]);
        } catch (\Exception $exception) {
            return response()->json([
                'code' => 'integration.validation_failed',
                'message' => __('api.integration.validation_failed', ['error' => $exception->getMessage()]),
            ], 400);
        }
    }
}
