use laravel::http::{IntoResponse, Redirect, Request, Response};
use crate::registry::{Registry, Settings};
pub async fn localized_fallback(request: Request) -> laravel::Result<Response> {
let registry = Registry::current();
let settings = registry.settings();
let path = request.path().trim_matches('/').to_owned();
if path.is_empty() && !settings.prefix(&settings.default_locale).is_empty() {
let preferred = preferred_locale(&settings);
let target = laravel::url::to(&format!("/{}", settings.prefix(&preferred)));
return Ok(Redirect::to(target)
.status(302)
.with_header("vary", "accept-language")
.with_header("cache-control", "no-store, private")
.into_response());
}
match resolve(&request, ®istry, &settings) {
Some(target) => Ok(Redirect::to(target)
.permanent()
.with_header("cache-control", format!("max-age={}", settings.redirect_max_age))
.into_response()),
None => Err(laravel::abort(404)),
}
}
fn preferred_locale(settings: &Settings) -> String {
let locale = laralocale::locale();
if settings.has_locale(&locale) {
locale
} else {
settings.default_locale.clone()
}
}
fn resolve(request: &Request, registry: &Registry, settings: &Settings) -> Option<String> {
if !matches!(request.method().as_str(), "GET" | "HEAD") {
return None;
}
let path = request.path().trim_matches('/');
if path.is_empty() {
return None;
}
let prefixes = settings.prefixes();
let bare = without_locale_prefix(path, &prefixes);
let mut order = vec![settings.default_locale.clone()];
order.extend(
settings
.locales
.iter()
.filter(|locale| **locale != settings.default_locale)
.cloned(),
);
for locale in order {
let Some((_, prefix)) = prefixes.iter().find(|(candidate, _)| *candidate == locale) else {
continue;
};
let candidate = format!("{prefix}/{bare}").trim_matches('/').to_owned();
if candidate == path {
continue;
}
if registry.serves(&format!("/{candidate}")) {
let url = laravel::url::to(&format!("/{candidate}"));
return Some(match request.uri().query() {
Some(query) if !query.is_empty() => format!("{url}?{query}"),
_ => url,
});
}
}
None
}
fn without_locale_prefix(path: &str, prefixes: &[(String, String)]) -> String {
for (_, prefix) in prefixes {
if prefix.is_empty() {
continue;
}
if path == prefix {
return String::new();
}
if let Some(rest) = path.strip_prefix(&format!("{prefix}/")) {
return rest.trim_matches('/').to_owned();
}
}
path.to_owned()
}