<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Models\User;
use App\Services\Localization\LocaleResolver;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\App;
use Illuminate\Validation\ValidationException;

class LocalizationController extends Controller
{
    public function context(Request $request, LocaleResolver $resolver): JsonResponse
    {
        $plane = $request->query('plane');
        $context = $request->attributes->get(LocaleResolver::REQUEST_ATTRIBUTE);

        if (is_string($plane) && $plane !== '') {
            $context = $resolver->resolve($request, $plane);
        }

        return response()->json(is_array($context) ? $context : $resolver->resolve($request));
    }

    public function updateOverride(Request $request): RedirectResponse
    {
        $locale = LocaleResolver::normalize($request->input('locale'));

        if ($locale === null) {
            throw ValidationException::withMessages([
                'locale' => [__('localization.validation.unsupported_locale')],
            ]);
        }

        $request->session()->put(LocaleResolver::SESSION_OVERRIDE_KEY, $locale);
        App::setLocale($locale);

        return back()->with('status', __('localization.notifications.locale_override_saved'));
    }

    public function clearOverride(Request $request, LocaleResolver $resolver): RedirectResponse
    {
        $request->session()->forget(LocaleResolver::SESSION_OVERRIDE_KEY);
        App::setLocale($resolver->resolve($request)['locale']);

        return back()->with('status', __('localization.notifications.locale_override_cleared'));
    }

    public function updateUserPreference(Request $request, LocaleResolver $resolver): RedirectResponse
    {
        $user = $request->user();

        abort_unless($user instanceof User, Response::HTTP_NOT_FOUND);

        $rawLocale = $request->input('preferred_locale');
        $locale = $rawLocale === null || $rawLocale === ''
            ? null
            : LocaleResolver::normalize($rawLocale);

        if ($rawLocale !== null && $rawLocale !== '' && $locale === null) {
            throw ValidationException::withMessages([
                'preferred_locale' => [__('localization.validation.unsupported_locale')],
            ]);
        }

        $user->forceFill(['preferred_locale' => $locale])->save();
        $user->refresh();

        App::setLocale($resolver->resolve($request)['locale']);

        return back()->with('status', $locale === null
            ? __('localization.notifications.user_preference_cleared')
            : __('localization.notifications.user_preference_saved'));
    }
}
