<?php

namespace App\Http\Controllers;

use App\Models\ImportedJob;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;

class JobNoteController extends Controller
{
    public function update(Request $request, ImportedJob $job): JsonResponse|RedirectResponse
    {
        Gate::authorize('view', $job);

        $validated = $request->validate([
            'body' => ['nullable', 'string', 'max:5000'],
        ]);

        $note = $request->user()->jobNotes()->updateOrCreate(
            ['imported_job_id' => $job->id],
            ['body' => $validated['body'] ?? null]
        );

        if ($request->expectsJson()) {
            return response()->json([
                'message' => 'Job note saved.',
                'body' => $note->body,
                'updated_at' => $note->updated_at?->toIso8601String(),
            ]);
        }

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