<?php

namespace Tests\Feature;

use App\Models\Payment;
use App\Models\Setting;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class WebhookTest extends TestCase
{
    use RefreshDatabase;

    public function test_webhook_endpoints_exist(): void
    {
        // No CSRF token required (exempted); M-Pesa returns the Daraja ack shape.
        $this->postJson('/webhooks/mpesa', [])->assertOk()->assertJson(['ResultCode' => 0]);
    }

    public function test_paystack_webhook_rejects_bad_signature(): void
    {
        Setting::put('paystack_secret_key', 'sk_test_secret', true);

        $this->call('POST', '/webhooks/paystack', [], [], [], [
            'HTTP_X-PAYSTACK-SIGNATURE' => 'wrong',
            'CONTENT_TYPE' => 'application/json',
        ], json_encode(['event' => 'charge.success', 'data' => ['reference' => 'r1']]))
            ->assertStatus(401);
    }

    public function test_paystack_webhook_marks_payment_paid(): void
    {
        $secret = 'sk_test_secret';
        Setting::put('paystack_secret_key', $secret, true);

        $payment = Payment::create([
            'gateway' => 'paystack',
            'reference' => 'ref-123',
            'amount' => 500000,
            'currency' => 'KES',
            'status' => 'pending',
            'purpose' => 'consultation',
        ]);

        $body = json_encode(['event' => 'charge.success', 'data' => ['reference' => 'ref-123', 'id' => 999]]);
        $signature = hash_hmac('sha512', $body, $secret);

        $this->call('POST', '/webhooks/paystack', [], [], [], [
            'HTTP_X-PAYSTACK-SIGNATURE' => $signature,
            'CONTENT_TYPE' => 'application/json',
        ], $body)->assertOk();

        $this->assertSame('paid', $payment->refresh()->status);
        $this->assertNotNull($payment->paid_at);
    }
}
