<?php

namespace App\Http\Controllers;

use App\Models\Language;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class LocaleController extends Controller
{
    public function __invoke(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'locale' => ['required', 'string', 'max:15'],
        ]);

        $language = Language::query()
            ->where('code', strtolower(str_replace('_', '-', trim($data['locale']))))
            ->where('is_active', true)
            ->firstOrFail();

        $request->session()->put('locale', $language->code);

        return back();
    }
}
