mod archive;
mod branch;
mod commit;
mod raw;
mod repo;
mod tag;
mod tree;

use std::collections::HashMap;
use std::path::{Component, PathBuf};

use axum::Router;
use axum::extract::{FromRequestParts, Path, State};
use axum::http::header;
use axum::http::request::Parts;
use axum::response::IntoResponse;
use axum::routing::get;
use jiff::Timestamp;
use jiff::tz::{Offset, TimeZone};

use crate::error::{Error, Result};

/// Returns the commit's author timestamp as Unix seconds.
pub(super) fn commit_timestamp(commit: &gix::Commit) -> Option<i64> {
    commit.time().ok().map(|t| t.seconds)
}

/// Formats a commit's author date as a `YYYY-MM-DD` string in the commit's
/// local timezone, returning `None` if the time cannot be parsed.
pub(super) fn commit_date(commit: &gix::Commit) -> Option<String> {
    let time = commit.time().ok()?;
    let zone = TimeZone::fixed(Offset::from_seconds(time.offset).ok()?);

    Timestamp::from_second(time.seconds)
        .map(|ts| ts.to_zoned(zone).date().to_string())
        .ok()
}

/// Formats a commit's committer date as a `YYYY-MM-DD` string in the
/// commit's local timezone, returning `None` if the time cannot be parsed.
pub(super) fn committer_date(commit: &gix::Commit) -> Option<String> {
    let sig = commit.committer().ok()?;
    let time = sig.time().ok()?;
    let zone = TimeZone::fixed(Offset::from_seconds(time.offset).ok()?);

    Timestamp::from_second(time.seconds)
        .map(|ts| ts.to_zoned(zone).date().to_string())
        .ok()
}

/// Axum extractor that pulls the `{repo}` path parameter and validates it
/// contains no path traversal components before passing it to handlers.
pub struct RepoName(pub String);

impl<S: Send + Sync> FromRequestParts<S> for RepoName {
    type Rejection = Error;

    async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self> {
        let Path(params) = Path::<HashMap<String, String>>::from_request_parts(parts, state)
            .await
            .map_err(|e| Error::BadRequest(e.to_string()))?;

        let name = params
            .get("repo")
            .ok_or_else(|| Error::BadRequest("missing repo parameter".to_string()))?
            .clone();

        // Reject names containing non-normal components (e.g. `..`) to prevent
        // directory traversal.
        if std::path::Path::new(&name)
            .components()
            .any(|c| !matches!(c, Component::Normal(_)))
        {
            return Err(Error::BadRequest("invalid repository name".to_string()));
        }

        Ok(RepoName(name))
    }
}

/// Shared application state passed to all route handlers.
#[derive(Clone)]
pub struct AppState {
    /// Path to the directory containing bare git repositories.
    pub root: PathBuf,
    /// Concatenated CSS served at `/style.css`.
    pub css: String,
}

/// Serves the concatenated stylesheet.
async fn style(State(state): State<AppState>) -> impl IntoResponse {
    (
        [(header::CONTENT_TYPE, "text/css; charset=utf-8")],
        state.css,
    )
}

/// Builds the application router with all routes and shared state attached.
pub fn router(state: AppState) -> Router {
    Router::new()
        .route("/style.css", get(style))
        .route("/", get(repo::list))
        .route("/{repo}", get(repo::detail))
        .route("/{repo}/tags", get(tag::list))
        .route("/{repo}/tags/{*tag}", get(tag::detail))
        .route("/{repo}/branches", get(branch::list))
        .route("/{repo}/branches/{*branch}", get(branch::detail))
        .route("/{repo}/commits", get(commit::list))
        .route("/{repo}/commits/{sha}", get(commit::detail))
        .route("/{repo}/commits/{sha}/tree", get(tree::handler))
        .route("/{repo}/commits/{sha}/tree/{*path}", get(tree::handler))
        .route("/{repo}/commits/{sha}/raw/{*path}", get(raw::handler))
        .route("/{repo}/archive/{format}/{*ref}", get(archive::handler))
        .with_state(state)
}
