<?php

namespace OtomaticAi\Jobs;

use OtomaticAi\Jobs\Contracts\ShouldHandle;
use OtomaticAi\Utils\Scheduler;
use OtomaticAi\Vendors\Illuminate\Support\Arr;

abstract class Job implements ShouldHandle
{
    const HOOK = "otomatic-ai-job";

    static public function dispatch($attrs, $priority = 10)
    {
        Scheduler::single(static::HOOK, [["class" => static::class, "attrs" => $attrs]], $priority);
    }

    static public function register()
    {
        Scheduler::register(static::HOOK, function ($args) {
            $class = Arr::get($args, "class");
            $attrs = Arr::get($args, "attrs", []);
            if ($class && class_exists($class)) {
                $job = new $class($attrs);
                $job->handle();
            }
        });
    }

    static public function search($attrs = [], $options = [])
    {
        $args = [
            "class" => static::class,
            "attrs" => $attrs,
        ];

        $actions = Scheduler::get(
            static::HOOK,
            [$args],
            $options,
        );

        return $actions;
    }
}
