<?php

namespace App\Modules\Settings\Localization\Controllers;

use App\Http\Controllers\Controller;
use App\Modules\Navigation\Services\NavigationService;
use App\Modules\Settings\Localization\Services\LanguageService;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;

class LocaleController extends Controller
{
    public function __construct(
        private readonly LanguageService $languageService,
    ) {}

    public function switch(Request $request, string $code): RedirectResponse
    {
        $language = $this->languageService->findActiveByCode($code);

        if (! $language) {
            return back()->with('error', __('languages.errors.not_available'));
        }

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

        if ($request->user() !== null) {
            NavigationService::forgetForUser($request->user());
        }

        return back()->with('status', __('languages.flash.switched', ['name' => $language->name]));
    }
}
