<?php

namespace App\Http\Controllers;

use App\Models\JobTitle;
use Cache;
use Illuminate\Http\Request;

class JobAutocompleteController extends Controller
{
    public function autocomplete(Request $request)
    {
        $query = trim($request->get('q', ''));

        // Require at least 2 characters to search
        if (strlen($query) < 2) {
            return response()->json([]);
        }

        // Use a cache key based on the query
        $cacheKey = 'job_autocomplete_' . strtolower($query);

        $formatted = Cache::remember($cacheKey, now()->addHours(12), function () use ($query) {
            // Search for job titles starting with the query (case-insensitive)
            $suggestions = JobTitle::where('job_title', 'LIKE', "{$query}%")
                ->limit(50)
                ->pluck('job_title');

            // Format for frontend
            return $suggestions->map(fn($title) => ['displayTitle' => $title]);
        });

        return response()->json($formatted);
    }
}
