<?php

namespace App\Services\Payments\Gateways;

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

class PaystackGateway implements PaymentGatewayInterface
{
    protected $secretKey;
    protected $baseUrl = 'https://api.paystack.co';

    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("Paystack credentials are not configured.");
        }

        $orderNumber = $metadata['order_number'];
        // Paystack requires unique reference IDs per attempt, so we append the timestamp
        $uniqueReference = $orderNumber . '_' . time();

        $response = Http::withToken($this->secretKey)
            ->post("{$this->baseUrl}/transaction/initialize", [
                'amount' => round($amount * 100), // Kobo/Cents
                'email' => auth()->user()->email ?? 'customer@example.com',
                'currency' => strtoupper($currency),
                'reference' => $uniqueReference,
                'callback_url' => route('payment.callback', ['gateway' => 'paystack', 'order' => $orderNumber]),
            ]);

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

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

    public function verify(array $requestData): array
    {
        $orderNumber = $requestData['order'] ?? null;
        $reference = $requestData['reference'] ?? null;

        if (!$reference) {
            return ['success' => false, 'order_number' => $orderNumber];
        }

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

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

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