<?php

namespace App\Http\Controllers;

use App\Exception\JobException;
use App\Models\Job;
use App\Services\BrowserJobsInstances;
use Cache;
use Illuminate\Http\Request;
use Inertia\Inertia;
use App\Exception\JobTestException;

class JobController extends Controller
{

    public function __construct(
        protected BrowserJobsInstances $jobInstances,
    ) {
    }

    public function show($jobId,  Request $request)
    {
        return Inertia::render('Job', [
            'job' => Job::where('id', $jobId)->with('jobInfos', 'jobRuns')->first(),
            'error' => $request->input('error'),
        ]);
    }

    public function update($jobId, Request $request)
    {
        $job = Job::where('id', $jobId)->first();
        $job->is_active = false; // Disable the job

        $errors = [];

        foreach ($job->jobInfos()->get() as $jobInfo) {
            $value = $request->input($jobInfo->id);
            if (!isset($value) && $jobInfo->is_required) {
                $errors[] = 'Le champ ' . $jobInfo->name . ' est requis.';
                continue;
            }

            Cache::forget($jobInfo->key);

            $jobInfo->value = $value;
            $jobInfo->save();
        }

        $job->save();

        if (count($errors) > 0) {
            return redirect()->route('jobs.show', ['job' => $job, 'error' => implode('<br />', $errors)]);
        }

        $job->is_active = $request->input('is_active');
        $job->save();

        return redirect()->route('jobs.show', ['job' => $job]);
    }

    public function test($jobId, Request $request)
    {
        $log = $this->jobInstances->getJobInstance($jobId)->executeTest();
        if (!empty($log)) {
            return response()->json(['artifact' => $log->load('artifacts')]);
        }
        return response()->json([]);
    }
}
