<?php

declare(strict_types=1);

use App\Models\PaymentGateway;
use App\Services\Billing\Gateway\YooKassaDriver;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Http;

uses(Tests\TestCase::class);

function fakeGateway(): PaymentGateway
{
    $gw = new PaymentGateway;
    $gw->code = 'yookassa';
    $gw->config = Crypt::encrypt(['shop_id' => 'shop_1', 'secret_key' => 'test_secret']);

    return $gw;
}

it('создаёт платёж и возвращает id + confirmation_url', function () {
    Http::fake([
        'api.yookassa.ru/v3/payments' => Http::response([
            'id' => '2da2b...test',
            'status' => 'pending',
            'confirmation' => ['type' => 'redirect', 'confirmation_url' => 'https://yoomoney.ru/checkout/2da2b'],
        ], 200),
    ]);

    $res = (new YooKassaDriver)->createPayment(
        fakeGateway(), '500.00', 'b3f1c2d4-0000-4000-8000-000000000001', 'https://liderra.ru/billing', null
    );

    expect($res->gatewayPaymentId)->toBe('2da2b...test')
        ->and($res->confirmationUrl)->toBe('https://yoomoney.ru/checkout/2da2b');

    Http::assertSent(function ($request) {
        return $request->hasHeader('Idempotence-Key', 'b3f1c2d4-0000-4000-8000-000000000001')
            && $request['amount']['value'] === '500.00'
            && $request['amount']['currency'] === 'RUB'
            && $request['capture'] === true;
    });
});

it('сверяет платёж и распознаёт succeeded', function () {
    Http::fake([
        'api.yookassa.ru/v3/payments/pay_77' => Http::response([
            'id' => 'pay_77',
            'status' => 'succeeded',
            'amount' => ['value' => '1000.00', 'currency' => 'RUB'],
            'payment_method' => ['type' => 'bank_card'],
        ], 200),
    ]);

    $res = (new YooKassaDriver)->verifyPayment(fakeGateway(), 'pay_77');

    expect($res->isSucceeded())->toBeTrue()
        ->and($res->amountRub)->toBe('1000.00')
        ->and($res->currency)->toBe('RUB')
        ->and($res->paymentMethod)->toBe('bank_card');
});
