1use askama::Template;
2use axum::{
3 Extension, Json,
4 extract::{Path, State},
5 http::StatusCode,
6 response::IntoResponse,
7};
8use serde::Deserialize;
9use std::sync::Arc;
10use uuid::Uuid;
11
12use crate::{AppState, jwt_auth::JWTAuthMiddleware, pages::HtmlTemplate};
13
14#[derive(Template)]
15#[template(path = "pages/tag/edit.html")]
16struct TagEditPage {
17 id: Uuid,
18 tag_name: String,
19 tag_value: String,
20 description: Option<String>,
21}
22
23pub async fn tag_edit_page(
24 State(_data): State<Arc<AppState>>,
25 Extension(jwt_auth): Extension<JWTAuthMiddleware>,
26 Path(id): Path<Uuid>,
27) -> Result<impl IntoResponse, (StatusCode, String)> {
28 let user = &jwt_auth.user;
29 let server_user = server::user::User { id: user.id };
30
31 let tag = server_user
32 .get_tag(id)
33 .await
34 .map_err(|e| (StatusCode::NOT_FOUND, format!("Tag not found: {e:?}")))?;
35
36 let template = TagEditPage {
37 id: tag.id,
38 tag_name: tag.tag_name,
39 tag_value: tag.tag_value,
40 description: tag.description,
41 };
42
43 Ok(HtmlTemplate(template))
44}
45
46#[derive(Deserialize)]
47pub struct TagEditForm {
48 id: Uuid,
49 tag_name: String,
50 tag_value: String,
51 description: Option<String>,
52}
53
54pub async fn edit_tag(
55 State(_data): State<Arc<AppState>>,
56 Extension(jwt_auth): Extension<JWTAuthMiddleware>,
57 Json(form): Json<TagEditForm>,
58) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
59 let user = &jwt_auth.user;
60 let server_user = server::user::User { id: user.id };
61
62 let description = form.description.filter(|desc| !desc.is_empty());
63
64 server_user
65 .update_tag(form.id, form.tag_name, form.tag_value, description)
66 .await
67 .map_err(|e| {
68 let error_response = serde_json::json!({
69 "status": "fail",
70 "message": t!("Failed to update tag"),
71 });
72 log::error!("Failed to update tag: {e:?}");
73 (StatusCode::INTERNAL_SERVER_ERROR, Json(error_response))
74 })?;
75
76 Ok(format!("{}: {}", t!("Tag updated"), form.id))
77}
78
79pub async fn delete_tag(
80 State(_data): State<Arc<AppState>>,
81 Extension(jwt_auth): Extension<JWTAuthMiddleware>,
82 Path(id): Path<Uuid>,
83) -> Result<impl IntoResponse, (StatusCode, Json<serde_json::Value>)> {
84 let user = &jwt_auth.user;
85 let server_user = server::user::User { id: user.id };
86
87 server_user.delete_tag(id).await.map_err(|e| {
88 let error_response = serde_json::json!({
89 "status": "fail",
90 "message": t!("Failed to delete tag"),
91 });
92 log::error!("Failed to delete tag: {e:?}");
93 (StatusCode::INTERNAL_SERVER_ERROR, Json(error_response))
94 })?;
95
96 Ok(t!("Tag deleted"))
97}