<?php

namespace App\Http\Controllers\Admin;

use App\FiveM\Models\JobDefinition;
use App\Http\Controllers\Controller;
use App\Http\Requests\Admin\StoreJobRequest;
use App\Models\AuditLog;
use Illuminate\Http\RedirectResponse;
use Inertia\Inertia;
use Inertia\Response;

class JobManagerController extends Controller
{
    public function index(): Response
    {
        return Inertia::render('Admin/Jobs/Index', [
            'jobs' => JobDefinition::query()->orderBy('label')->get(),
        ]);
    }

    public function store(StoreJobRequest $request): RedirectResponse
    {
        $job = JobDefinition::updateOrCreate(
            ['name' => $request->validated('name')],
            ['label' => $request->validated('label'), 'grades' => $request->validated('grades') ?? []]
        );

        AuditLog::record('job.saved', null, $job->only(['name', 'label']));

        return back()->with('success', 'Job saved.');
    }

    public function update(StoreJobRequest $request, JobDefinition $job): RedirectResponse
    {
        $job->update($request->validated());

        AuditLog::record('job.updated', $job, $request->validated());

        return back()->with('success', 'Job updated.');
    }
}
