<?php

use App\Application\Services\ApiCredentialService;
use App\Models\Merchant;
use Illuminate\Contracts\Http\Kernel;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

$merchant = Merchant::where('status', 'active')->whereNotNull('email_verified_at')->first();
if (! $merchant) {
    throw new RuntimeException('No active verified merchant found.');
}

$issued = app(ApiCredentialService::class)->issue($merchant, config('gateway.environment'), [
    'payments:read', 'payments:write', 'payouts:read', 'payouts:write', 'balances:read', 'webhooks:write', 'merchants:read', 'merchants:write', 'wallets:read', 'wallets:write',
]);

$kernel = app(Kernel::class);

$send = function (string $method, string $path, array $payload = [], array $extraHeaders = []) use ($issued, $kernel) {
    $body = $payload === [] ? '' : json_encode($payload, JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR);
    $timestamp = (string) now()->timestamp;
    $nonce = (string) Str::ulid();
    $canonical = implode("\n", [$method, $path, $timestamp, $nonce, hash('sha256', $body)]);
    $signature = hash_hmac('sha256', $canonical, $issued['secret']);

    $server = [
        'HTTP_ACCEPT' => 'application/json',
        'CONTENT_TYPE' => 'application/json',
        'HTTP_X_API_KEY' => $issued['public_key'],
        'HTTP_X_API_TIMESTAMP' => $timestamp,
        'HTTP_X_API_NONCE' => $nonce,
        'HTTP_X_API_SIGNATURE' => 'v1='.$signature,
    ];

    foreach ($extraHeaders as $key => $value) {
        $server['HTTP_'.strtoupper(str_replace('-', '_', $key))] = $value;
    }

    $request = Request::create($path, $method, [], [], [], $server, $body);
    $response = $kernel->handle($request);
    $decoded = json_decode($response->getContent(), true);
    $kernel->terminate($request, $response);

    return [$response->getStatusCode(), $decoded ?: $response->getContent()];
};

$order = 'SMOKE-'.Str::ulid();
[$invoiceStatus, $invoice] = $send('POST', '/api/v1/invoices', [
    'price_amount' => '10.00',
    'price_currency' => 'USD',
    'pay_currency' => 'USDTTRC20',
    'order_id' => $order,
    'payer' => ['email' => 'smoke@example.com', 'name' => 'Smoke Test'],
    'items' => [['name' => 'Test item', 'quantity' => 1, 'unit_amount' => '10.00']],
], ['Idempotency-Key' => 'smoke-invoice-'.$order]);

$invoiceId = $invoice['data']['invoice_id'] ?? null;
[$checkoutStatus, $checkout] = $send('GET', '/api/v1/checkout/'.$invoiceId);
[$planStatus, $plan] = $send('POST', '/api/v1/subscriptions/plans', [
    'name' => 'Smoke Monthly',
    'price_amount' => '12.00',
    'price_currency' => 'USD',
    'pay_currency' => 'USDTTRC20',
    'interval' => 'month',
]);
$planId = $plan['data']['id'] ?? null;
[$subStatus, $sub] = $send('POST', '/api/v1/subscriptions', [
    'plan_id' => $planId,
    'customer' => ['email' => 'subscriber@example.com', 'name' => 'Subscriber'],
]);
[$batchStatus, $batch] = $send('POST', '/api/v1/payout-batches', [
    'pay_currency' => 'USDTTRC20',
    'items' => [['to_address' => 'TST_SMOKE_ADDRESS_12345', 'amount' => '1.50']],
]);
$batchId = $batch['data']['id'] ?? null;
[$approveStatus, $approve] = $send('POST', '/api/v1/payout-batches/'.$batchId.'/approve');

$result = [
    'invoice' => [$invoiceStatus, $invoiceId, $invoice['success'] ?? false],
    'checkout' => [$checkoutStatus, $checkout['success'] ?? false],
    'plan' => [$planStatus, $planId, $plan['success'] ?? false],
    'subscription' => [$subStatus, $sub['data']['id'] ?? null, $sub['success'] ?? false],
    'payout_batch' => [$batchStatus, $batchId, $batch['success'] ?? false],
    'payout_batch_approve' => [$approveStatus, $approve['data']['status'] ?? null, $approve['success'] ?? false],
];

dump($result);
