<?php

namespace App\Modules\Admin\Tenancy\Services;

use App\Models\User;
use App\Modules\Admin\Tenancy\Models\Tenant;
use App\Modules\Admin\Tenancy\Notifications\PlanLimitAlmostReachedNotification;
use App\Modules\Admin\Tenancy\Notifications\PlanLimitBlockedAttemptNotification;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Notification;

class PlanLimitNotifier
{
    public function notifyAlmostReachedIfNeeded(
        Tenant $tenant,
        string $limitKey,
        int $used,
        int $cap,
    ): void {
        $cacheKey = sprintf('plan_ntf:almost:%d:%s:%d', $tenant->id, $limitKey, $cap);
        if (! Cache::add($cacheKey, 1, now()->addDays(7))) {
            return;
        }
        $recipients = $this->tenantRecipients($tenant);
        if ($recipients->isEmpty()) {
            return;
        }
        Notification::send(
            $recipients,
            new PlanLimitAlmostReachedNotification($limitKey, $used, $cap),
        );
    }

    public function notifyBlockedIfNeeded(
        Tenant $tenant,
        string $limitKey,
        int $used,
        int $cap,
    ): void {
        $cacheKey = sprintf('plan_ntf:blocked:%d:%s', $tenant->id, $limitKey);
        if (! Cache::add($cacheKey, 1, now()->addHour())) {
            return;
        }
        $recipients = $this->tenantRecipients($tenant);
        if ($recipients->isEmpty()) {
            return;
        }
        Notification::send(
            $recipients,
            new PlanLimitBlockedAttemptNotification($limitKey, $used, $cap),
        );
    }

    /**
     * @return Collection<int, User>
     */
    private function tenantRecipients(Tenant $tenant): Collection
    {
        $admins = User::query()
            ->where('tenant_id', $tenant->id)
            ->where('is_admin', true)
            ->get();
        if ($admins->isNotEmpty()) {
            return $admins;
        }

        return User::query()->where('tenant_id', $tenant->id)->get();
    }
}
