<?php

declare(strict_types=1);

namespace App\Services\Billing\Gateway;

use App\Models\PaymentGateway;
use Illuminate\Support\Facades\Http;
use RuntimeException;

/**
 * Драйвер ЮKassa (YooKassa API v3).
 * Auth: Basic shopId:secretKey. Idempotence-Key — заголовок при создании.
 * Чек 54-ФЗ передаётся секцией receipt (включается флагом billing_receipt_enabled).
 */
final class YooKassaDriver implements PaymentGatewayDriver
{
    private const BASE = 'https://api.yookassa.ru/v3';

    public function createPayment(
        PaymentGateway $gateway,
        string $amountRub,
        string $idempotenceKey,
        string $returnUrl,
        ?array $receipt,
    ): CreatePaymentResult {
        [$shopId, $secret] = $this->creds($gateway);

        $payload = [
            'amount' => ['value' => $amountRub, 'currency' => 'RUB'],
            'capture' => true,
            'confirmation' => ['type' => 'redirect', 'return_url' => $returnUrl],
            'description' => 'Пополнение баланса Лидерра',
        ];
        if ($receipt !== null) {
            $payload['receipt'] = $receipt;
        }

        $resp = Http::withBasicAuth($shopId, $secret)
            ->withHeaders(['Idempotence-Key' => $idempotenceKey])
            ->acceptJson()
            ->post(self::BASE.'/payments', $payload);

        if (! $resp->successful()) {
            throw new RuntimeException('YooKassa createPayment failed: HTTP '.$resp->status().' body='.$resp->body());
        }

        $id = (string) $resp->json('id');
        $url = (string) $resp->json('confirmation.confirmation_url');
        if ($id === '' || $url === '') {
            throw new RuntimeException('YooKassa createPayment: пустой id/confirmation_url');
        }

        return new CreatePaymentResult($id, $url);
    }

    public function verifyPayment(PaymentGateway $gateway, string $gatewayPaymentId): WebhookVerifyResult
    {
        [$shopId, $secret] = $this->creds($gateway);

        $resp = Http::withBasicAuth($shopId, $secret)
            ->acceptJson()
            ->get(self::BASE.'/payments/'.$gatewayPaymentId);

        if (! $resp->successful()) {
            throw new RuntimeException('YooKassa verifyPayment failed: HTTP '.$resp->status().' body='.$resp->body());
        }

        return new WebhookVerifyResult(
            gatewayPaymentId: (string) $resp->json('id'),
            status: (string) $resp->json('status'),
            amountRub: (string) $resp->json('amount.value'),
            currency: (string) $resp->json('amount.currency'),
            paymentMethod: $resp->json('payment_method.type'),
        );
    }

    /** @return array{0:string,1:string} [shopId, secretKey] */
    private function creds(PaymentGateway $gateway): array
    {
        $c = $gateway->credentials();
        $shopId = (string) ($c['shop_id'] ?? '');
        $secret = (string) ($c['secret_key'] ?? '');
        if ($shopId === '' || $secret === '') {
            throw new RuntimeException('YooKassa: shop_id/secret_key не настроены');
        }

        return [$shopId, $secret];
    }
}
