<?php

namespace Pixeldev\SquareWooSync\Tools;

use Pixeldev\SquareWooSync\Square\SquareHelper;

if (!defined('ABSPATH')) {
    exit;
}

/**
 * Helper for running arbitrary Square API requests using the stored access token.
 * Powers the Tools → API Tester page.
 */
class ApiTester
{
    private SquareHelper $helper;

    public function __construct()
    {
        $this->helper = new SquareHelper();
    }

    /**
     * Execute a Square API request.
     *
     * @param string      $endpoint Endpoint beginning with `/`.
     * @param string      $method   HTTP verb.
     * @param string|null $body     Raw JSON body or null.
     */
    public function run_request(string $endpoint, string $method = 'GET', ?string $body = null): array
    {
        $payload = null;
        if ($body !== null && $body !== '') {
            $decoded = json_decode($body, true);
            if ($decoded === null && json_last_error() !== JSON_ERROR_NONE) {
                return ['success' => false, 'error' => 'Invalid JSON body'];
            }
            $payload = $decoded;
        }

        return $this->helper->square_api_request($endpoint, strtoupper($method), $payload);
    }
}
