<?php

namespace App\Services;

use App\Models\Call;
use App\Models\Transaction;
use Illuminate\Support\Facades\Cache;

class CallCreditService
{
    /**
     * Check whether a profile has sufficient credits to publish calls.
     * Uses the same budget logic as Pay.php: balance - limit_min > 0.
     */
    public static function profileHasCredits(string $profileType, int $profileId): bool
    {
        $profile = $profileType::find($profileId);
        if (!$profile) {
            return false;
        }

        $accounts = $profile->accounts()->notRemoved()->get();
        if ($accounts->isEmpty()) {
            return false;
        }

        foreach ($accounts as $account) {
            $balance = Transaction::where('from_account_id', $account->id)
                ->orWhere('to_account_id', $account->id)
                ->selectRaw('SUM(CASE WHEN to_account_id = ? THEN amount ELSE -amount END) as balance', [$account->id])
                ->value('balance') ?? 0;

            if (($balance - $account->limit_min) > 0) {
                return true;
            }
        }

        return false;
    }

    /**
     * Pause all active calls for a profile (set till = now, remove from index).
     */
    public static function pauseAllActiveCalls(string $profileType, int $profileId): void
    {
        $activeCalls = Call::where('callable_type', $profileType)
            ->where('callable_id', $profileId)
            ->where(fn ($q) => $q->whereNull('till')->orWhere('till', '>', now()))
            ->get();

        foreach ($activeCalls as $call) {
            $call->update(['till' => now()]);
            $call->unsearchable();
        }
    }
}
