<?php

namespace Fitsmart\PaypalParcels\ExternalService\ParcelPanel;

use Fitsmart\PaypalParcels\Config;
use Fitsmart\PaypalParcels\Contract\ApiClientInterface;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Monolog\Logger;

class ParcelpanelApiClient implements ApiClientInterface
{
    private Client $client;
    private Logger $logger;

    public function __construct(Logger $logger)
    {
        $this->logger = $logger;
        $config = Config::getConfigPart('parcelpanel') ?? [];
        $this->client = new Client([
            'base_uri' => $config['base_uri'] ?? 'https://wp-api.parcelpanel.com/api/v1/',
            'headers' => [
                'Content-Type' => 'application/json',
                'PP-Api-Key' => Config::getEnv('PP_PARCELPANEL_API_KEY', ''),
            ]
        ]);
    }

    public function createTracking(array $payload): bool
    {
        try {
            $response = $this->client->post('tracking/create', [
                'json' => $payload,
            ]);

            $status = $response->getStatusCode();

            if ($status >= 200 && $status < 300) {
                $this->logger->info('Tracking sent', $payload);
                return true;
            }

            $this->logger->error('ParcelPanel error response', [
                'status' => $status,
                'body' => $response->getBody()->getContents(),
            ]);
        } catch (GuzzleException $e) {
            $this->logger->error('PayPal request failed: ' . $e->getMessage());
        }

        return false;
    }
}
