<?php

declare(strict_types=1);

namespace Bot\Infrastructure\Repository;

use Bot\Domain\Entity\Payment;
use Bot\Domain\Repository\PaymentRepositoryInterface;

/**
 * پیاده‌سازی in-memory برای پرداخت‌ها.
 */
final class InMemoryPaymentRepository implements PaymentRepositoryInterface
{
    /** @var array<int,Payment> keyed by id */
    private array $paymentsById = [];
    private int $nextId = 1;

    public function findById(int $id): ?Payment
    {
        return $this->paymentsById[$id] ?? null;
    }

    public function findByPayload(string $payload): ?Payment
    {
        foreach ($this->paymentsById as $payment) {
            if ($payment->getPayload() === $payload) {
                return $payment;
            }
        }
        return null;
    }

    public function findByExternalId(string $externalId): ?Payment
    {
        foreach ($this->paymentsById as $payment) {
            if ($payment->getExternalId() === $externalId) {
                return $payment;
            }
        }
        return null;
    }

    public function save(Payment $payment): void
    {
        $id = $payment->getId();
        
        // اگر payment جدید است (id=0)، یک Payment جدید با ID تولید می‌کنیم
        if ($id === 0) {
            $payment = new Payment(
                $this->nextId++,
                $payment->getUserId(),
                $payment->getGateway(),
                $payment->getAmount(),
                $payment->getStatus(),
                $payment->getExternalId(),
                $payment->getPayload(),
            );
            $id = $payment->getId();
        }
        
        $this->paymentsById[$id] = $payment;
    }
}


