<?php

namespace App\Jobs;

use App\Repositories\MikrotikRepository;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;

class AutoConnectMikrotikJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function handle(MikrotikRepository $repository)
    {
        $servers = $repository->query()->where('status', true)->get();

        foreach ($servers as $server) {
            $sync = Cache::get('mikrotik:sync:'.$server->id, []);
            $retryAfter = $sync['retry_after'] ?? null;
            if ($retryAfter && Carbon::parse($retryAfter)->isFuture()) {
                continue;
            }
            TestMikrotikConnectionJob::dispatch($server->id);
        }
    }
}
