<?php

namespace App\Sms\Service;

use App\Payment\Entity\Payment;
use App\Sms\Entity\SmsWallet;
use App\Sms\Entity\SmsWalletTransaction;
use App\Sms\Repository\SmsWalletRepository;
use App\Sms\Repository\SmsWalletTransactionRepository;

class SmsWalletService
{
    public function __construct(
        private readonly SmsWalletRepository            $walletRepo,
        private readonly SmsWalletTransactionRepository $txRepo,
    ) {}

    public function getOrCreate(string $entityType, int $entityId): SmsWallet
    {
        $wallet = $this->walletRepo->findByEntity($entityType, $entityId);
        if ($wallet === null) {
            $wallet = new SmsWallet($entityType, $entityId);
            $this->walletRepo->save($wallet);
        }
        return $wallet;
    }

    public function charge(SmsWallet $wallet, int $amountRials, Payment $payment): void
    {
        $wallet->credit($amountRials);
        $this->walletRepo->save($wallet);

        $tx = new SmsWalletTransaction(
            $wallet,
            SmsWalletTransaction::TYPE_CREDIT,
            $amountRials,
            'شارژ کیف پیامک',
            $payment
        );
        $this->txRepo->save($tx);
    }

    public function deduct(SmsWallet $wallet, int $amountRials, string $description): bool
    {
        if (!$wallet->debit($amountRials)) {
            return false;
        }
        $this->walletRepo->save($wallet);

        $tx = new SmsWalletTransaction(
            $wallet,
            SmsWalletTransaction::TYPE_DEBIT,
            $amountRials,
            $description,
            null
        );
        $this->txRepo->save($tx);

        return true;
    }

    public function getBalance(string $entityType, int $entityId): int
    {
        return $this->walletRepo->getBalance($entityType, $entityId);
    }
}
