<?php

namespace App\Services;

use App\Models\SmsWallet;
use RuntimeException;

class SmsWalletService
{
    public function ensureCanSend(int $schoolId, int $recipientCount): void
    {
        $wallet = SmsWallet::query()->firstOrCreate(['school_id' => $schoolId]);
        $cost = $recipientCount * (int) config('daneshyar.sms_cost_per_successful_recipient', 1);

        if ($wallet->balance < $cost) {
            throw new RuntimeException('موجودی کیف پول SMS کافی نیست.');
        }
    }

    public function chargeSuccessfulRecipients(int $schoolId, int $successCount): void
    {
        $cost = $successCount * (int) config('daneshyar.sms_cost_per_successful_recipient', 1);

        SmsWallet::query()->where('school_id', $schoolId)->decrement('balance', $cost);
        SmsWallet::query()->where('school_id', $schoolId)->increment('total_used', $cost);
    }
}
