/*
    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 crate::{helper::A, ui::error::MyResult};
use jellycommon::{
    api::NodeFilterSort,
    routes::u_node_id,
    user::{NodeUserData, WatchedState},
    NodeID,
};
use jellylogic::{
    node::{
        get_node, update_node_userdata_rating, update_node_userdata_watched,
        update_node_userdata_watched_progress,
    },
    session::Session,
};
use rocket::{
    form::Form, get, post, response::Redirect, serde::json::Json, FromForm, FromFormField,
    UriDisplayQuery,
};

#[derive(Debug, FromFormField, UriDisplayQuery)]
pub enum UrlWatchedState {
    None,
    Watched,
    Pending,
}

#[get("/n/<id>/userdata")]
pub fn r_node_userdata(session: A<Session>, id: A<NodeID>) -> MyResult<Json<NodeUserData>> {
    let u = get_node(&session.0, id.0, false, false, NodeFilterSort::default())?.userdata;
    Ok(Json(u))
}

#[post("/n/<id>/watched?<state>")]
pub async fn r_node_userdata_watched(
    session: A<Session>,
    id: A<NodeID>,
    state: UrlWatchedState,
) -> MyResult<Redirect> {
    update_node_userdata_watched(
        &session.0,
        id.0,
        match state {
            UrlWatchedState::None => WatchedState::None,
            UrlWatchedState::Watched => WatchedState::Watched,
            UrlWatchedState::Pending => WatchedState::Pending,
        },
    )?;
    Ok(Redirect::found(u_node_id(id.0)))
}

#[derive(FromForm)]
pub struct UpdateRating {
    #[field(validate = range(-10..=10))]
    rating: i32,
}

#[post("/n/<id>/update_rating", data = "<form>")]
pub async fn r_node_userdata_rating(
    session: A<Session>,
    id: A<NodeID>,
    form: Form<UpdateRating>,
) -> MyResult<Redirect> {
    update_node_userdata_rating(&session.0, id.0, form.rating)?;
    Ok(Redirect::found(u_node_id(id.0)))
}

#[post("/n/<id>/progress?<t>")]
pub async fn r_node_userdata_progress(session: A<Session>, id: A<NodeID>, t: f64) -> MyResult<()> {
    update_node_userdata_watched_progress(&session.0, id.0, t)?;
    Ok(())
}
