use actix_web::{HttpResponse, web};
use serde::{Deserialize, Serialize};
use service::AppService;
use service::git::compare::CompareResponse;
use session::Session;

use crate::error::ApiError;

fn ok_json<T: Serialize>(data: T) -> Result<HttpResponse, ApiError> {
    Ok(HttpResponse::Ok().json(data))
}

#[derive(Deserialize, utoipa::IntoParams)]
pub struct WkRepoPath {
    pub wk: String,
    pub repo: String,
}

#[utoipa::path(
    get, path = "/api/v1/workspace/{wk}/repos/{repo}/compare/{basehead}",
    params(
        ("wk" = String, Path),
        ("repo" = String, Path),
        ("basehead" = String, Path, description = "Comparison in format 'base...head'"),
    ),
    responses((status = 200, body = CompareResponse)),
    security(("session" = []))
)]
pub async fn compare(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<(String, String, String)>,
) -> Result<HttpResponse, ApiError> {
    let (wk, repo_name, basehead) = path.into_inner();

    let (base, head) = basehead.split_once("...").ok_or_else(|| {
        ApiError(service::error::AppError::BadRequest(
            "basehead must be in format 'base...head'".to_string(),
        ))
    })?;

    ok_json(
        service
            .git_compare(&session, &wk, &repo_name, base, head)
            .await?,
    )
}
