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

use crate::error::ApiError;
use crate::git::dto;

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,
}

#[derive(Deserialize, utoipa::IntoParams)]
pub struct BlameQuery {
    pub path: String,
    pub rev: Option<String>,
    pub start_line: Option<u32>,
    pub end_line: Option<u32>,
}
#[utoipa::path(
    get, path = "/api/v1/workspace/{wk}/repos/{repo}/git/blame",
    params(WkRepoPath, BlameQuery),
    responses((status = 200, description = "Blame result", body = dto::BlameFileResponseDto)),
    security(("session" = []))
)]
pub async fn blame_file(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<WkRepoPath>,
    query: web::Query<BlameQuery>,
) -> Result<HttpResponse, ApiError> {
    let WkRepoPath { wk, repo } = path.into_inner();

    match (query.start_line, query.end_line) {
        (Some(start), Some(end)) => {
            let data: dto::BlameFileResponseDto = service
                .git_blame_hunk(
                    &session,
                    &wk,
                    &repo,
                    query.path.clone(),
                    query.rev.clone(),
                    start,
                    end,
                )
                .await?
                .into();
            ok_json(data)
        }
        _ => {
            let data: dto::BlameFileResponseDto = service
                .git_blame_file(
                    &session,
                    &wk,
                    &repo,
                    query.path.clone(),
                    query.rev.clone(),
                    None,
                )
                .await?
                .into();
            ok_json(data)
        }
    }
}
