<?php

namespace App\Services;

use GuzzleHttp\Exception\ClientException;
use Illuminate\Support\Facades\Log;

class AutoTraderIntegrationsApi
{
    protected AutoTraderApi $api;

    public function __construct()
    {
        $config = config('auto_trader_stock', []);
        $config['use_live_api'] = !$config['use_sandbox'];

        $this->api = new AutoTraderApi($config);
    }

    /**
     * Get list of integrations the partner has access to.
     *
     * Each integration has an integrationId, name, type (API | Datafeeds |
     * Exports) and an array of capability objects (each with a `name`).
     *
     * @see https://developers.autotrader.co.uk/api#integrations-api-(beta)
     */
    public function getIntegrations(): array
    {
        try {
            $data = $this->api->get('integrations');

            return [
                'success' => true,
                'integrations' => $data['results'] ?? [],
            ];
        } catch (ClientException $exception) {
            Log::error('Autotrader Integrations API error', [
                'message' => $exception->getMessage(),
                'response' => (string) $exception->getResponse()->getBody(),
            ]);
            return [
                'success' => false,
                'error' => $this->parseErrorResponse($exception),
            ];
        } catch (\Exception $exception) {
            Log::error('Autotrader Integrations API error', [
                'message' => $exception->getMessage(),
            ]);
            return [
                'success' => false,
                'error' => $exception->getMessage(),
            ];
        }
    }

    /**
     * Get details for a specific integration.
     */
    public function getIntegration(string $integrationId): array
    {
        try {
            $data = $this->api->get('integrations/' . urlencode($integrationId));

            return [
                'success' => true,
                'integration' => $data['results'][0] ?? $data,
            ];
        } catch (ClientException $exception) {
            $statusCode = $exception->getResponse()->getStatusCode();
            if ($statusCode === 403 || $statusCode === 404) {
                return [
                    'success' => false,
                    'error' => "No access to integration ID: {$integrationId}",
                    'accessible' => false,
                ];
            }

            Log::error('Autotrader Integration API error', [
                'integration_id' => $integrationId,
                'message' => $exception->getMessage(),
                'response' => (string) $exception->getResponse()->getBody(),
            ]);
            return [
                'success' => false,
                'error' => $this->parseErrorResponse($exception),
            ];
        } catch (\Exception $exception) {
            Log::error('Autotrader Integration API error', [
                'integration_id' => $integrationId,
                'message' => $exception->getMessage(),
            ]);
            return [
                'success' => false,
                'error' => $exception->getMessage(),
            ];
        }
    }

    protected function parseErrorResponse(ClientException $exception): string
    {
        try {
            $body = json_decode((string) $exception->getResponse()->getBody(), true);
            return $body['message'] ?? $body['error'] ?? $exception->getMessage();
        } catch (\Exception $e) {
            return $exception->getMessage();
        }
    }
}
