<?php

namespace App\Services\Payment\Drivers;

use App\Models\SubscriptionPayment;
use App\Services\Payment\Contracts\PaymentDriver;
use App\Services\Payment\PaymentIntent;
use Illuminate\Support\Facades\Http;

class WompiDriver implements PaymentDriver
{
    public function __construct(protected array $config = [])
    {
    }

    public function createIntent(SubscriptionPayment $payment): PaymentIntent
    {
        $baseUrl = $this->baseUrl();
        $amountInCents = (int) round(((float) $payment->amount) * 100);

        $payload = [
            'amount_in_cents' => $amountInCents,
            'currency' => $payment->currency,
            'customer_email' => $payment->company?->email,
            'reference' => $payment->reference,
            'redirect_url' => route('tenant.payments.index'),
            'signature:integrity' => $this->integritySignature($payment->reference, $amountInCents, $payment->currency),
        ];

        if (blank($this->config['private_key'] ?? null)) {
            return new PaymentIntent(
                reference: $payment->reference,
                status: 'pending',
                payload: $payload + ['configured' => false],
            );
        }

        $response = Http::withToken($this->config['private_key'])
            ->acceptJson()
            ->post($baseUrl.'/v1/transactions', $payload)
            ->json();

        $data = $response['data'] ?? [];

        return new PaymentIntent(
            reference: $payment->reference,
            status: $data['status'] ?? 'pending',
            redirectUrl: $data['payment_link_url'] ?? null,
            externalId: $data['id'] ?? null,
            payload: $response,
        );
    }

    public function verifyWebhook(array $payload, ?string $signature = null): bool
    {
        $secret = $this->config['events_secret'] ?? null;

        if (! $secret || ! $signature) {
            return false;
        }

        return hash_equals(hash_hmac('sha256', json_encode($payload), $secret), $signature);
    }

    protected function integritySignature(string $reference, int $amountInCents, string $currency): string
    {
        $key = (string) ($this->config['integrity_key'] ?? '');

        return hash('sha256', $reference.$amountInCents.$currency.$key);
    }

    protected function baseUrl(): string
    {
        return ($this->config['environment'] ?? 'test') === 'production'
            ? 'https://production.wompi.co'
            : 'https://sandbox.wompi.co';
    }
}
