/*
    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::error::MyResult;
use crate::request_info::RequestInfo;
use anyhow::{Context, Result};
use jellycommon::{Nku, jellyobject::EMPTY};
use jellydb::{Query, helper::DatabaseReturnExt};
use jellyui::components::home::{Home, HomeRow};
use rocket::{get, response::content::RawHtml};
use std::{borrow::Cow, str::FromStr};

#[get("/home")]
pub fn r_home(ri: RequestInfo<'_>) -> MyResult<RawHtml<String>> {
    ri.require_user()?;

    let mut rows = Vec::new();
    rows.push(home_row(
        &ri,
        "home.bin.latest_video",
        "FILTER (visi = visi AND kind = vide) SORT DESCENDING BY FIRST rldt",
    )?);
    rows.push(home_row(
        &ri,
        "home.bin.latest_music",
        "FILTER (visi = visi AND kind = musi) SORT DESCENDING BY FIRST rldt",
    )?);
    rows.extend(home_row_highlight(
        &ri,
        "home.bin.daily_random",
        "FILTER (visi = visi AND kind = movi) SORT RANDOM",
    )?);
    rows.push(home_row(
        &ri,
        "home.bin.max_rating",
        "SORT DESCENDING BY FIRST rtng.imdb",
    )?);
    rows.extend(home_row_highlight(
        &ri,
        "home.bin.daily_random",
        "FILTER (visi = visi AND kind = show) SORT RANDOM",
    )?);

    Ok(ri.respond_ui(&Home {
        ri: &ri.render_info(),
        rows: &rows,
    }))
}

fn home_row(
    ri: &RequestInfo<'_>,
    title: &'static str,
    query: &str,
) -> Result<(&'static str, HomeRow<'static>)> {
    let q = Query::from_str(query).context("parse query")?;
    ri.state.database.transaction_ret(|txn| {
        let rows = txn.query(q.clone())?.take(16).collect::<Result<Vec<_>>>()?;

        let mut nkus = Vec::new();
        for (row, _) in rows {
            let node = txn.get(row)?.unwrap();
            nkus.push(Nku {
                node: Cow::Owned(node),
                role: None,
                userdata: Cow::Borrowed(EMPTY),
            });
        }
        Ok((title, HomeRow::Inline(nkus)))
    })
}

fn home_row_highlight(
    ri: &RequestInfo<'_>,
    title: &'static str,
    query: &str,
) -> Result<Option<(&'static str, HomeRow<'static>)>> {
    let q = Query::from_str(query).context("parse query")?;
    ri.state.database.transaction_ret(|txn| {
        let Some(row) = txn.query(q.clone())?.next() else {
            return Ok(None);
        };
        let row = row?.0;
        let node = txn.get(row)?.unwrap();
        Ok(Some((
            title,
            HomeRow::Highlight(Nku {
                node: Cow::Owned(node),
                role: None,
                userdata: Cow::Borrowed(EMPTY),
            }),
        )))
    })
}
