use rocket::response::Redirect;
use rocket_dyn_templates::{context, Template};

use crate::{
	db::{doll, schema::DollTagsDb},
	ids::id_public_to_db,
	pages::CommonTemplateState,
};

use super::error_handlers::PageResult;

#[get("/?<miss>&<ident>&<microchip_id>")]
pub fn index(
	miss: Option<bool>,
	ident: Option<&str>,
	microchip_id: Option<&str>,
	meta: CommonTemplateState,
) -> Template {
	Template::render(
		"index",
		context! {
			meta,
			miss,
			ident,
			microchip_id,
		},
	)
}

#[get("/profile/<id>")]
pub fn short_url(id: &str) -> Redirect {
	Redirect::to(uri!(show_profile(Some(id), Some(""))))
}

#[get("/profile?<ident>&<microchip_id>")]
pub async fn show_profile(
	mut db: DollTagsDb,
	ident: Option<&str>,
	microchip_id: Option<&str>,
	meta: CommonTemplateState,
) -> PageResult {
	let internal_id = ident.and_then(|v| id_public_to_db(v)).unwrap_or(0);
	let microchip_id = microchip_id.unwrap_or("");

	let profile = match doll::get(&mut *db, internal_id, microchip_id, false).await? {
		Some(p) => p,
		None => return Ok(Redirect::to(uri!(index(Some(true), ident, Some(microchip_id)))).into()),
	};

	let has_notable_traits = profile.has_notable_traits();
	let has_chassis_info = profile.chassis_id.is_some()
		&& profile.chassis_type.is_some()
		&& profile.chassis_color.is_some();

	debug!("showing profile: {:?}", profile);
	Ok(Template::render(
		"show_profile",
		context! {
			meta,
			profile,
			has_notable_traits,
			has_chassis_info,
		},
	)
	.into())
}
