/*
    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::request_info::RequestInfo;
use crate::routes::error::MyResult;
use anyhow::anyhow;
use jellycommon::{
    IDENT_YOUTUBE_VIDEO, NO_IDENTIFIERS, NO_SLUG, jellyobject::Path, routes::u_node_id,
};
use jellydb::{Filter, Query};
use rocket::{get, response::Redirect};

#[get("/watch?<v>")]
pub fn r_youtube_watch(ri: RequestInfo<'_>, v: &str) -> MyResult<Redirect> {
    if v.len() != 11 {
        Err(anyhow!("video id length incorrect"))?
    }
    let mut res = None;
    ri.state.database.transaction(&mut |txn| {
        if let Some(row) = txn.query_single(Query {
            filter: Filter::Match(
                Path(vec![NO_IDENTIFIERS.0, IDENT_YOUTUBE_VIDEO.0]),
                v.into(),
            ),
            ..Default::default()
        })? {
            res = txn.get(row)?;
        }
        Ok(())
    })?;
    let node = res.ok_or(anyhow!("video not found"))?;
    let slug = node.get(NO_SLUG).ok_or(anyhow!("node has no slug"))?;
    Ok(Redirect::found(u_node_id(slug)))
}

#[get("/channel/<id>")]
pub fn r_youtube_channel(_ri: RequestInfo<'_>, id: &str) -> MyResult<Redirect> {
    let _ = id;
    // 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)))
    todo!()
}

#[get("/embed/<v>")]
pub fn r_youtube_embed(_ri: RequestInfo<'_>, v: &str) -> MyResult<Redirect> {
    let _ = v;
    // 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)))
    todo!()
}
