use actix_web::{HttpResponse, web};
use serde::{Deserialize, Serialize};
use service::AppService;
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(
    post, path = "/api/v1/workspace/{wk}/repos/{repo}/git/watch",
    params(WkRepoPath), request_body = Object, description = "WatchLevel {level: String}",
    responses((status = 200, description = "Watch result")),
    security(("session" = []))
)]
pub async fn watch_repo(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<WkRepoPath>,
    body: web::Json<serde_json::Value>,
) -> Result<HttpResponse, ApiError> {
    let WkRepoPath { wk, repo } = path.into_inner();
    let level = body.get("level").and_then(|v| v.as_str()).map(String::from);
    let data = service.git_repo_watch(&session, &wk, &repo, level).await?;
    ok_json(data)
}
#[utoipa::path(
    delete, path = "/api/v1/workspace/{wk}/repos/{repo}/git/watch",
    params(WkRepoPath),
    responses((status = 200, description = "Watch result")),
    security(("session" = []))
)]
pub async fn unwatch_repo(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<WkRepoPath>,
) -> Result<HttpResponse, ApiError> {
    let WkRepoPath { wk, repo } = path.into_inner();
    let data = service.git_repo_unwatch(&session, &wk, &repo).await?;
    ok_json(data)
}
#[utoipa::path(
    get, path = "/api/v1/workspace/{wk}/repos/{repo}/git/watch",
    params(WkRepoPath),
    responses((status = 200, description = "Watch status")),
    security(("session" = []))
)]
pub async fn watch_status(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<WkRepoPath>,
) -> Result<HttpResponse, ApiError> {
    let WkRepoPath { wk, repo } = path.into_inner();
    let data = service.git_repo_watch_status(&session, &wk, &repo).await?;
    ok_json(data)
}
