<?php

namespace App\Services\DecisionEvents\Handlers;

use App\Jobs\EndFieldJob;
use App\Services\DecisionEvents\Contracts\DecisionEventHandler;
use App\Services\DecisionEvents\DecisionEventContext;
use Illuminate\Support\Facades\Bus;

class EndFieldJobHandler implements DecisionEventHandler
{
    /**
     * Config contract:
     * - any pass-through keys needed by the EndFieldJob implementation
     */
    public function handle(DecisionEventContext $context, array $config = []): void
    {
        $activity = $context->activity;
        $job = new EndFieldJob(
            activityId: (int) $activity->id,
            contractId: $activity->contract_id ? (int) $activity->contract_id : null,
            config: $config,
        );

        // Run synchronously in local/dev/testing or when debug is on or queue driver is sync; otherwise queue it.
        $shouldRunSync = app()->environment(['local', 'development', 'dev', 'testing'])
            || (bool) config('app.debug')
            || config('queue.default') === 'sync';

        if ($shouldRunSync) {
            Bus::dispatchSync($job);
        } else {
            dispatch($job);
        }
    }
}
