<?php

use Modules\Payment\Contracts\PaymentGatewayInterface;
use Modules\Payment\Data\PaymentRequestData;
use Modules\Payment\Data\PaymentResultData;
use Modules\Payment\Data\RefundResultData;
use Modules\Payment\Enums\PaymentMethod;
use Modules\Payment\Enums\PaymentStatus;
use Modules\Payment\Factories\PaymentGatewayFactory;
use Modules\Payment\Gateways\KbzMiniAppGateway;

/**
 * Stands in for "a second gateway" being added — proves call sites that only
 * depend on PaymentGatewayFactory (never a concrete gateway class) don't
 * need to change when a gateway implementation is swapped/added.
 */
class FakePaymentGateway implements PaymentGatewayInterface
{
    public function initiate(PaymentRequestData $data): PaymentResultData
    {
        return new PaymentResultData(status: PaymentStatus::Pending, gatewayTransactionId: 'fake-txn', gatewayPayload: []);
    }

    public function verify(string $gatewayTransactionId): PaymentResultData
    {
        return new PaymentResultData(status: PaymentStatus::Completed, gatewayTransactionId: $gatewayTransactionId, gatewayPayload: []);
    }

    public function refund(string $gatewayTransactionId, string $amount, string $reason): RefundResultData
    {
        throw new RuntimeException('not needed for this test');
    }

    public function handleWebhook(array $payload): PaymentResultData
    {
        throw new RuntimeException('not needed for this test');
    }
}

test('the factory resolves KbzMiniAppGateway for the KbzMiniApp method by default', function () {
    $gateway = app(PaymentGatewayFactory::class)->make(PaymentMethod::KbzMiniApp);

    expect($gateway)->toBeInstanceOf(KbzMiniAppGateway::class);
});

test('registering a fake gateway swaps the resolved implementation with no call-site changes', function () {
    $factory = app(PaymentGatewayFactory::class);
    $factory->register(PaymentMethod::KbzMiniApp, FakePaymentGateway::class);

    // A call site that only knows about the factory + interface, never the
    // concrete gateway class — this is exactly what an Action/controller does.
    $callSite = fn (PaymentGatewayFactory $factory, PaymentMethod $method): PaymentGatewayInterface => $factory->make($method);

    expect($callSite($factory, PaymentMethod::KbzMiniApp))->toBeInstanceOf(FakePaymentGateway::class);
});

test('the factory throws when no gateway is registered for a method', function () {
    $factory = new PaymentGatewayFactory;

    expect(fn () => $factory->make(PaymentMethod::KbzMiniApp))->toThrow(RuntimeException::class);
});

test('the factory is bound as a singleton', function () {
    expect(app(PaymentGatewayFactory::class))->toBe(app(PaymentGatewayFactory::class));
});
