/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2026 metamuffin <metamuffin.org>
*/
use super::format_form_error;
use crate::{
    helper::{RequestInfo, A},
    ui::error::MyResult,
};
use jellycommon::{
    routes::u_account_settings,
    user::{PlayerKind, Theme},
};
use jellylogic::account::{
    update_user_display_name, update_user_native_secret, update_user_password,
    update_user_player_preference, update_user_theme,
};
use jellyui::{account::settings::SettingsPage, locale::tr, render_page, scaffold::SessionInfo};
use rocket::{
    form::{self, validate::len, Contextual, Form},
    get, post,
    request::FlashMessage,
    response::{content::RawHtml, Flash, Redirect},
    FromForm,
};
use std::ops::Range;

#[derive(FromForm)]
pub struct SettingsForm {
    #[field(validate = option_len(4..64))]
    password: Option<String>,
    #[field(validate = option_len(4..32))]
    display_name: Option<String>,
    theme: Option<A<Theme>>,
    player_preference: Option<A<PlayerKind>>,
    native_secret: Option<String>,
}

fn option_len<'v>(value: &Option<String>, range: Range<usize>) -> form::Result<'v, ()> {
    value.as_ref().map(|v| len(v, range)).unwrap_or(Ok(()))
}

#[get("/account/settings")]
pub fn r_account_settings(ri: RequestInfo, flash: Option<FlashMessage>) -> RawHtml<String> {
    RawHtml(render_page(
        &SettingsPage {
            flash: &flash.map(FlashMessage::into_inner),
            session: &SessionInfo {
                user: ri.session.user.clone(),
            },
            lang: &ri.lang,
        },
        ri.render_info(),
    ))
}

#[post("/account/settings", data = "<form>")]
pub fn r_account_settings_post(
    ri: RequestInfo,
    form: Form<Contextual<SettingsForm>>,
) -> MyResult<Flash<Redirect>> {
    let form = match &form.value {
        Some(v) => v,
        None => {
            return Ok(Flash::error(
                Redirect::to(u_account_settings()),
                format_form_error(form),
            ));
        }
    };

    let mut out = String::new();

    if let Some(password) = &form.password {
        update_user_password(&ri.session, password)?;
        out += &*tr(ri.lang, "settings.account.password.changed");
        out += "\n";
    }
    if let Some(display_name) = &form.display_name {
        update_user_display_name(&ri.session, display_name)?;
        out += &*tr(ri.lang, "settings.account.display_name.changed");
        out += "\n";
    }
    if let Some(theme) = form.theme {
        update_user_theme(&ri.session, theme.0)?;
        out += &*tr(ri.lang, "settings.account.theme.changed");
        out += "\n";
    }
    if let Some(player_preference) = form.player_preference {
        update_user_player_preference(&ri.session, player_preference.0)?;
        out += &*tr(ri.lang, "settings.player_preference.changed");
        out += "\n";
    }
    if let Some(native_secret) = &form.native_secret {
        update_user_native_secret(&ri.session, native_secret)?;
        out += &*tr(ri.lang, "settings.native_secret.changed");
        out += "\n";
    }
    let out = if out.is_empty() {
        tr(ri.lang, "settings.no_change").to_string()
    } else {
        out
    };

    Ok(Flash::success(Redirect::to(u_account_settings()), out))
}
