/*
    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 anyhow::anyhow;
use jellycommon::{
    routes::{u_node_slug, u_node_slug_player},
    IdentifierType,
};
use jellylogic::{
    node::{get_node_by_eid, node_id_to_slug},
    session::Session,
};
use rocket::{get, response::Redirect};

#[get("/watch?<v>")]
pub fn r_youtube_watch(session: A<Session>, v: &str) -> MyResult<Redirect> {
    if v.len() != 11 {
        Err(anyhow!("video id length incorrect"))?
    }
    let Some(id) = get_node_by_eid(&session.0, IdentifierType::YoutubeVideo, v)? else {
        Err(anyhow!("element not found"))?
    };
    let slug = node_id_to_slug(&session.0, id)?;
    Ok(Redirect::to(u_node_slug_player(&slug)))
}

#[get("/channel/<id>")]
pub fn r_youtube_channel(session: A<Session>, id: &str) -> MyResult<Redirect> {
    let Some(id) = (if id.starts_with("UC") {
        get_node_by_eid(&session.0, IdentifierType::YoutubeChannel, id)?
    } else if id.starts_with("@") {
        get_node_by_eid(&session.0, IdentifierType::YoutubeChannelHandle, id)?
    } else {
        Err(anyhow!("unknown channel id format"))?
    }) else {
        Err(anyhow!("channel not found"))?
    };
    let slug = node_id_to_slug(&session.0, id)?;
    Ok(Redirect::to(u_node_slug(&slug)))
}

#[get("/embed/<v>")]
pub fn r_youtube_embed(session: A<Session>, v: &str) -> MyResult<Redirect> {
    if v.len() != 11 {
        Err(anyhow!("video id length incorrect"))?
    }
    let Some(id) = get_node_by_eid(&session.0, IdentifierType::YoutubeVideo, v)? else {
        Err(anyhow!("element not found"))?
    };
    let slug = node_id_to_slug(&session.0, id)?;
    Ok(Redirect::to(u_node_slug_player(&slug)))
}
