<?php

use App\Models\Town;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;

Route::get('/', fn () => redirect()->route('dashboard'));

// Auth
Route::livewire('/login', 'auth.login')->name('login')->middleware('guest');
Route::post('/logout', function () {
    Auth::logout();
    session()->invalidate();
    session()->regenerateToken();

    return redirect()->route('login');
})->name('logout')->middleware('auth');

// Town autocomplete search
Route::middleware(['auth'])->get('/towns/search', function (Request $request) {
    $query = $request->string('query')->trim();

    if ($query->length() < 2) {
        return response()->json([]);
    }

    $towns = Town::active()
        ->search($query)
        ->when($request->filled('state'), fn ($q) => $q->where('state', $request->integer('state')))
        ->orderBy('town_name')
        ->limit(10)
        ->get(['town_name', 'state']);

    return response()->json(
        $towns->map(fn ($town) => [
            'name' => $town->town_name,
            'state' => $town->state->abbreviation(),
            'label' => $town->town_name.', '.$town->state->abbreviation(),
        ])
    );
})->name('towns.search');

// Authenticated
Route::middleware(['auth'])->group(function () {
    Route::livewire('/dashboard', 'dashboard')->name('dashboard');
    Route::livewire('/travel-requests/create', 'travel-request.create')->name('travel-requests.create');
    Route::livewire('/travel-requests/{id}', 'travel-request.show')->name('travel-requests.show');
    Route::livewire('/travel-requests/{id}/approve', 'travel-request.approve')
        ->name('travel-requests.approve')
        ->middleware('role:travel_approver|administrator');
});
