use leptos::*;
use leptos_router::Redirect;

#[server]
async fn logout_action() -> Result<(), ServerFnError<String>> {
    use crate::domain::api::prelude::*;

    let session = use_context::<Session>().unwrap();
    session.clear();

    Ok(())
}

#[component]
pub fn LogoutPage(user_signal: RwSignal<bool>) -> impl IntoView {
    let submit = Action::<LogoutAction, _>::server();
    let response = submit.value().read_only();

    create_effect(move |_| {
        if response.get().is_some() {
            user_signal.set(!user_signal.get_untracked());
        }
    });

    submit.dispatch(LogoutAction {});

    view! {
        <Suspense>
            <Show when=move || response().is_some()>
                <Redirect path="/" />
            </Show>
        </Suspense>
    }
}
