<?php

namespace App\Services;

use App\Models\IntegrationLog;
use GuzzleHttp\Client as HttpClient;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Support\Facades\Log;

class VetorClient
{
    protected HttpClient $http;

    public function __construct(?HttpClient $http = null)
    {
        $this->http = $http ?: new HttpClient([
            'base_uri' => rtrim(config('services.vetor.api_url', ''), '/') . '/',
            'timeout' => 30,
            'headers' => [
                'Authorization' => config('services.vetor.authorization', ''),
                'Accept' => 'application/json',
            ],
            'verify' => false, // Apenas para desenvolvimento
        ]);
    }

    /**
     * Busca produtos no Vetor ERP
     * 
     * @param array $filters Filtros OData (ex: ['$filter' => "contains(descricao, 'dipirona')"])
     * @return array
     */
    public function getProducts(array $filters = []): array
    {
        try {
            $queryString = !empty($filters) ? '?' . http_build_query($filters) : '';
            $response = $this->http->get('api/ecommerce/produtos/consulta' . $queryString);
            $data = json_decode((string) $response->getBody(), true);

            if (!isset($data['status']) || $data['status'] !== 200) {
                IntegrationLog::write('vetor_products_error', ['response' => $data]);
                throw new \RuntimeException('Resposta inválida da API Vetor: ' . json_encode($data));
            }

            IntegrationLog::write('vetor_products_fetched', [
                'count' => $data['total'] ?? 0,
                'filters' => $filters
            ]);

            return $data['data'] ?? [];
        } catch (RequestException $e) {
            $code = $e->getResponse() ? $e->getResponse()->getStatusCode() : 0;
            IntegrationLog::write('vetor_request_failed', [
                'endpoint' => 'produtos',
                'filters' => $filters,
                'error' => $e->getMessage(),
                'status' => $code,
            ]);
            throw $e;
        }
    }

    public function postOrder(array $order): void
    {
        // Exemplo de envio (ajuste para a API real do Vetor)
        $this->http->post('orders', [ 'json' => $order ]);
        IntegrationLog::write('vetor_order_posted', ['order_id' => $order['id'] ?? null]);
    }

    public function getStockLevels(): array
    {
        // Exemplo (ajuste para endpoint real)
        // return json_decode((string)$this->http->get('stock-levels')->getBody(), true) ?: [];
        return [];
    }
}
