<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class PaymentGatewayService
{
    protected string $baseUrl;

    protected ?string $apiKey;

    public function __construct()
    {
        $this->baseUrl = config('services.payment_gateway.url', 'http://localhost:3000/api/payment');
        $this->apiKey = config('services.payment_gateway.api_key');
    }

    /**
     * Get all active payment channels.
     */
    public function getChannels(): array
    {
        try {
            $response = Http::timeout(10)
                ->get("{$this->baseUrl}/channels");

            if ($response->successful()) {
                $data = $response->json();

                return [
                    'success' => true,
                    'data' => $data['data'] ?? [],
                ];
            }

            return [
                'success' => false,
                'error' => $response->json()['message'] ?? 'Failed to fetch payment channels',
            ];
        } catch (\Exception $e) {
            Log::error('Payment Gateway: Failed to get channels', [
                'error' => $e->getMessage(),
            ]);

            return [
                'success' => false,
                'error' => 'Failed to connect to payment gateway',
            ];
        }
    }

    /**
     * Calculate fee for payment channel.
     */
    public function calculateFee(string $channelCode, int $amount): array
    {
        try {
            $response = Http::timeout(10)
                ->post("{$this->baseUrl}/fee-calculator", [
                    'channel_code' => $channelCode,
                    'amount' => $amount,
                ]);

            if ($response->successful()) {
                $data = $response->json();

                return [
                    'success' => true,
                    'data' => $data['data'] ?? [],
                ];
            }

            return [
                'success' => false,
                'error' => $response->json()['message'] ?? 'Failed to calculate fee',
            ];
        } catch (\Exception $e) {
            Log::error('Payment Gateway: Failed to calculate fee', [
                'error' => $e->getMessage(),
                'channel_code' => $channelCode,
                'amount' => $amount,
            ]);

            return [
                'success' => false,
                'error' => 'Failed to connect to payment gateway',
            ];
        }
    }

    /**
     * Create payment transaction.
     */
    public function createPayment(array $paymentData): array
    {
        try {
            $response = Http::timeout(30)
                ->post("{$this->baseUrl}/create", $paymentData);

            if ($response->successful()) {
                $data = $response->json();

                return [
                    'success' => true,
                    'data' => $data['data'] ?? [],
                ];
            }

            $errorMessage = $response->json()['message'] ?? 'Failed to create payment';
            $errors = $response->json()['errors'] ?? null;

            Log::warning('Payment Gateway: Failed to create payment', [
                'error' => $errorMessage,
                'errors' => $errors,
                'payment_data' => $paymentData,
            ]);

            return [
                'success' => false,
                'error' => $errorMessage,
                'errors' => $errors,
            ];
        } catch (\Exception $e) {
            Log::error('Payment Gateway: Failed to create payment', [
                'error' => $e->getMessage(),
                'payment_data' => $paymentData,
            ]);

            return [
                'success' => false,
                'error' => 'Failed to connect to payment gateway',
            ];
        }
    }

    /**
     * Get transaction status.
     */
    public function getTransactionStatus(string $reference, ?string $refId = null): array
    {
        try {
            $response = Http::timeout(10)
                ->post("{$this->baseUrl}/transactions", [
                    'ref' => $reference,
                    'ref_id' => $refId,
                ]);

            if ($response->successful()) {
                $data = $response->json();

                return [
                    'success' => true,
                    'data' => $data['data'] ?? [],
                ];
            }

            return [
                'success' => false,
                'error' => $response->json()['message'] ?? 'Failed to get transaction status',
            ];
        } catch (\Exception $e) {
            Log::error('Payment Gateway: Failed to get transaction status', [
                'error' => $e->getMessage(),
                'reference' => $reference,
                'ref_id' => $refId,
            ]);

            return [
                'success' => false,
                'error' => 'Failed to connect to payment gateway',
            ];
        }
    }
}
