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/star",
    params(WkRepoPath),
    responses((status = 200, description = "Star/unstar result")),
    security(("session" = []))
)]
pub async fn star_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_star(&session, &wk, &repo).await?;
    ok_json(data)
}

#[utoipa::path(
    delete, path = "/api/v1/workspace/{wk}/repos/{repo}/git/star",
    params(WkRepoPath),
    responses((status = 200, description = "Star/unstar result")),
    security(("session" = []))
)]
pub async fn unstar_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_unstar(&session, &wk, &repo).await?;
    ok_json(data)
}

#[utoipa::path(
    get, path = "/api/v1/workspace/{wk}/repos/{repo}/git/star",
    params(WkRepoPath),
    responses((status = 200, description = "Star status")),
    security(("session" = []))
)]
pub async fn star_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_star_status(&session, &wk, &repo).await?;
    ok_json(data)
}
