<?php
namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\{Router, Plan, Voucher, User};
use App\Services\Routeros\MikrotikService;

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

    public function __construct(
        public Router $router, public Plan $plan, public int $qty, public User $user
    ){}

    public function handle(MikrotikService $mt)
    {
        $svc = $mt->using($this->router)->connect();
        for ($i=0; $i<$this->qty; $i++) {
            $code = strtoupper(bin2hex(random_bytes(3)));
            $svc->createVoucher($code, $code, [
                'rate_limit' => $this->plan->rate_limit,
                'validity'   => $this->plan->validity,
                'data_cap_mb'=> $this->plan->data_cap_mb,
            ]);
            Voucher::create([
                'router_id'=>$this->router->id,
                'plan_id'=>$this->plan->id,
                'code'=>$code,
                'password'=>$code,
                'status'=>'issued',
                'sold_by_user_id'=>$this->user->id
            ]);
        }
    }
}
