<?php

namespace App\Payment\Gateway;

class MockGateway implements PaymentGatewayInterface
{
    public function getName(): string { return 'mock'; }

    public function isConfigured(): bool { return true; }

    public function initiate(int $amountRials, string $orderId, string $callbackUrl): PaymentInitResult
    {
        $redirectUrl = $callbackUrl . '&mock=1&ResCode=0&RefId=MOCK-' . $orderId;
        return new PaymentInitResult(true, redirectUrl: $redirectUrl, token: 'MOCK-' . $orderId);
    }

    public function verify(array $callbackData): PaymentVerifyResult
    {
        $mock    = $callbackData['mock'] ?? '0';
        $resCode = $callbackData['ResCode'] ?? ($callbackData['State'] ?? '');

        if ($mock !== '1' && $mock !== 1) {
            return new PaymentVerifyResult(false, errorMessage: 'mock callback مجاز نیست');
        }

        if (($callbackData['cancel'] ?? '0') === '1' || $resCode === '17') {
            return new PaymentVerifyResult(false, errorMessage: 'پرداخت توسط کاربر لغو شد', canceled: true);
        }

        $refId = $callbackData['RefId'] ?? $callbackData['order_id'] ?? 'MOCK-REF';

        // Simulate a gateway that reports the settled amount (like SEP's
        // AffectiveAmount) so the controller's amount-mismatch guard is exercisable.
        $amount = (int) ($callbackData['mock_amount'] ?? 0);

        return new PaymentVerifyResult(true, referenceId: $refId, amountRials: $amount);
    }

    public function refund(string $saleOrderId, string $saleReferenceId, int $refundAmountRials): PaymentRefundResult
    {
        return new PaymentRefundResult(true, refundRefId: 'MOCK-REFUND-' . $saleOrderId);
    }

    public function reverse(string $saleOrderId, string $saleReferenceId): PaymentRefundResult
    {
        return new PaymentRefundResult(true);
    }
}
