//! Route handlers for tag pages.
//!
//! Covers two routes: the tag list (`/{repo}/tags`) and the tag detail page
//! (`/{repo}/tags/{*tag}`).  The detail handler peels the tag ref to its
//! commit and presents a release-oriented view with the annotation message,
//! commit info, and archive download links.

use askama::Template;
use askama_web::WebTemplate;
use axum::extract::{Path, State};
use axum::response::IntoResponse;
use serde::Deserialize;

use crate::error::Result;
use crate::git;
use crate::routes::{AppState, RepoName};

#[derive(Deserialize)]
pub(super) struct TagPath {
    tag: String,
}

/// Template context for the tag list page.
#[derive(Template, WebTemplate)]
#[template(path = "tag_list.html")]
struct TagList {
    repo: String,
    tags: Vec<git::TagInfo>,
}

/// Template context for the tag detail page.
#[derive(Template, WebTemplate)]
#[template(path = "tag_detail.html")]
struct TagDetail {
    repo: String,
    tag: String,
    tagger: Option<String>,
    tag_date: Option<String>,
    message: Option<String>,
    commit_sha: String,
    commit_author: String,
    commit_date: String,
}

/// Renders the full list of tags for a repository, sorted newest first.
pub async fn list(
    State(state): State<AppState>,
    RepoName(repo): RepoName,
) -> Result<impl IntoResponse> {
    let git_repo = git::open_repo(&state.root, &repo)?;
    let tags = git::load_tags(&git_repo);
    Ok(TagList { repo, tags })
}

/// Renders the detail page for a single tag.
pub async fn detail(
    State(state): State<AppState>,
    RepoName(repo): RepoName,
    Path(params): Path<TagPath>,
) -> Result<impl IntoResponse> {
    let git_repo = git::open_repo(&state.root, &repo)?;
    let (annotation, commit) = git::load_tag(&git_repo, &params.tag)?;

    Ok(TagDetail {
        repo,
        tag: params.tag,
        tagger: annotation.tagger,
        tag_date: annotation.date,
        message: annotation.message,
        commit_sha: commit.sha,
        commit_author: commit.author,
        commit_date: commit.date,
    })
}
