<?php

declare(strict_types=1);

namespace GalpaoImperial\Api;

final class AsaasClient
{
    private string $baseUrl;
    private ?string $token;

    public function __construct()
    {
        loadEnv(dirname(__DIR__, 2));

        $environment = env('ASAAS_ENVIRONMENT', 'sandbox');
        $this->baseUrl = $environment === 'production'
            ? 'https://api.asaas.com/v3'
            : 'https://api-sandbox.asaas.com/v3';
        $this->token = env('ASAAS_API_KEY');
    }

    public function isEnabled(): bool
    {
        return $this->token !== null && $this->token !== '';
    }

    public function createOrUpdateCustomer(array $payload): array
    {
        return $this->request('POST', '/customers', $payload);
    }

    public function createPixPayment(array $payload): array
    {
        return $this->createPayment($payload);
    }

    public function createPayment(array $payload): array
    {
        return $this->request('POST', '/payments', $payload);
    }

    public function getPixQrCode(string $paymentId): array
    {
        return $this->request('GET', '/payments/' . urlencode($paymentId) . '/pixQrCode');
    }

    public function getPayment(string $paymentId): array
    {
        return $this->request('GET', '/payments/' . urlencode($paymentId));
    }

    public function createTransfer(array $payload): array
    {
        return $this->request('POST', '/transfers', $payload);
    }

    private function request(string $method, string $path, ?array $payload = null): array
    {
        if (!$this->isEnabled()) {
            throw new HttpException(503, 'ASAAS_API_KEY não configurada no ambiente.');
        }

        $url = $this->baseUrl . $path;
        $curl = curl_init($url);

        if ($curl === false) {
            throw new HttpException(500, 'Não foi possível iniciar a conexão com o Asaas.');
        }

        $headers = [
            'Content-Type: application/json',
            'accept: application/json',
            'access_token: ' . $this->token,
            'User-Agent: GalpaoImperial/1.0',
        ];

        curl_setopt_array($curl, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST => strtoupper($method),
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_PROXY => '',
            CURLOPT_NOPROXY => '*',
        ]);

        if ($payload !== null && strtoupper($method) !== 'GET') {
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
        }

        $response = curl_exec($curl);
        $status = (int) curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
        $error = curl_error($curl);
        curl_close($curl);

        if ($response === false) {
            throw new HttpException(502, 'Falha ao comunicar com o Asaas.', ['curlError' => $error]);
        }

        $decoded = json_decode($response, true);
        if (!is_array($decoded)) {
            throw new HttpException(502, 'Resposta inválida recebida do Asaas.');
        }

        if ($status >= 400) {
            throw new HttpException($status, 'Erro retornado pelo Asaas.', ['asaas' => $decoded]);
        }

        return $decoded;
    }
}
