<?php

namespace App\Services\Payments\Gateways;

use App\Services\Payments\PaymentGatewayInterface;
use Illuminate\Support\Facades\Http;
use Exception;

class FlutterwaveGateway implements PaymentGatewayInterface
{
    protected $secretKey;
    protected $baseUrl = 'https://api.flutterwave.com/v3';

    public function __construct($config, $mode)
    {
        $credentials = ($mode === 'live') ? $config['live_credentials'] : $config['test_credentials'];
        $this->secretKey = $credentials['secret_key'] ?? '';
    }

    public function pay(float $amount, string $currency, array $metadata)
    {
        if (empty($this->secretKey)) {
            throw new Exception("Flutterwave credentials are not configured.");
        }

        $orderNumber = $metadata['order_number'];
        $uniqueReference = $orderNumber . '_' . time();

        $response = Http::withToken($this->secretKey)
            ->post("{$this->baseUrl}/payments", [
                'tx_ref' => $uniqueReference,
                'amount' => $amount, // Standard Decimal
                'currency' => strtoupper($currency),
                'redirect_url' => route('payment.callback', ['gateway' => 'flutterwave', 'order' => $orderNumber]),
                'customer' => [
                    'email' => auth()->user()->email ?? 'customer@example.com',
                    'name' => auth()->user()->name ?? 'Customer',
                ],
                'customizations' => [
                    'title' => config('app.name') . ' Checkout',
                    'description' => 'Payment for order ' . $orderNumber,
                ]
            ]);

        if ($response->successful() && $response->json('data.link')) {
            return ['url' => $response->json('data.link')];
        }

        throw new Exception("Flutterwave Transaction Failed: " . $response->body());
    }

    public function verify(array $requestData): array
    {
        $orderNumber = $requestData['order'] ?? null;
        $transactionId = $requestData['transaction_id'] ?? null; // Returned by Flutterwave
        $status = $requestData['status'] ?? null;

        if (!$transactionId || $status !== 'successful') {
            return ['success' => false, 'order_number' => $orderNumber];
        }

        // Secure server-to-server check
        $response = Http::withToken($this->secretKey)
            ->get("{$this->baseUrl}/transactions/{$transactionId}/verify");

        $isSuccess = false;
        if ($response->successful()) {
            $isSuccess = $response->json('data.status') === 'successful';
        }

        return [
            'success' => $isSuccess,
            'order_number' => $orderNumber
        ];
    }
}