use actix_web::{HttpResponse, web};
use serde::{Deserialize, Serialize};
use service::AppService;
use service::git::release::{CreateRelease, ReleaseResponse, UpdateRelease};
use session::Session;
use uuid::Uuid;

use crate::error::ApiError;

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

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

fn ok_empty() -> Result<HttpResponse, ApiError> {
    Ok(HttpResponse::NoContent().finish())
}

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

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

#[utoipa::path(
    get, path = "/api/v1/workspace/{wk}/repos/{repo}/releases",
    params(WkRepoPath),
    responses((status = 200, body = Vec<ReleaseResponse>)),
    security(("session" = []))
)]
pub async fn list_releases(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<WkRepoPath>,
) -> Result<HttpResponse, ApiError> {
    let user_id = session
        .user()
        .ok_or(ApiError(service::error::AppError::Unauthorized))?;
    ok_json(
        service
            .git_release_list_by_name(&session, user_id, &path.wk, &path.repo)
            .await?,
    )
}

#[utoipa::path(
    get, path = "/api/v1/workspace/{wk}/repos/{repo}/releases/{id}",
    params(ReleaseIdPath),
    responses((status = 200, body = ReleaseResponse)),
    security(("session" = []))
)]
pub async fn get_release(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<ReleaseIdPath>,
) -> Result<HttpResponse, ApiError> {
    let user_id = session
        .user()
        .ok_or(ApiError(service::error::AppError::Unauthorized))?;
    ok_json(
        service
            .git_release_get_by_name(
                &session, user_id, &path.wk, &path.repo, path.id,
            )
            .await?,
    )
}

#[utoipa::path(
    get, path = "/api/v1/workspace/{wk}/repos/{repo}/releases/tags/{tag}",
    params(WkRepoPath, ("tag" = String, Path)),
    responses((status = 200, body = ReleaseResponse)),
    security(("session" = []))
)]
pub async fn get_release_by_tag(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<(String, String, String)>,
) -> Result<HttpResponse, ApiError> {
    let (wk, repo_name, tag) = path.into_inner();
    let user_id = session
        .user()
        .ok_or(ApiError(service::error::AppError::Unauthorized))?;
    ok_json(
        service
            .git_release_get_by_tag_name(
                &session, user_id, &wk, &repo_name, &tag,
            )
            .await?,
    )
}

#[utoipa::path(
    post, path = "/api/v1/workspace/{wk}/repos/{repo}/releases",
    params(WkRepoPath),
    request_body = CreateRelease,
    responses((status = 201, body = ReleaseResponse)),
    security(("session" = []))
)]
pub async fn create_release(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<WkRepoPath>,
    body: web::Json<CreateRelease>,
) -> Result<HttpResponse, ApiError> {
    let user_id = session
        .user()
        .ok_or(ApiError(service::error::AppError::Unauthorized))?;
    ok_created(
        service
            .git_release_create_by_name(
                &session,
                user_id,
                &path.wk,
                &path.repo,
                body.into_inner(),
            )
            .await?,
    )
}

#[utoipa::path(
    patch, path = "/api/v1/workspace/{wk}/repos/{repo}/releases/{id}",
    params(ReleaseIdPath),
    request_body = UpdateRelease,
    responses((status = 200, body = ReleaseResponse)),
    security(("session" = []))
)]
pub async fn update_release(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<ReleaseIdPath>,
    body: web::Json<UpdateRelease>,
) -> Result<HttpResponse, ApiError> {
    let user_id = session
        .user()
        .ok_or(ApiError(service::error::AppError::Unauthorized))?;
    ok_json(
        service
            .git_release_update_by_name(
                &session,
                user_id,
                &path.wk,
                &path.repo,
                path.id,
                body.into_inner(),
            )
            .await?,
    )
}

#[utoipa::path(
    delete, path = "/api/v1/workspace/{wk}/repos/{repo}/releases/{id}",
    params(ReleaseIdPath),
    responses((status = 204)),
    security(("session" = []))
)]
pub async fn delete_release(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<ReleaseIdPath>,
) -> Result<HttpResponse, ApiError> {
    let user_id = session
        .user()
        .ok_or(ApiError(service::error::AppError::Unauthorized))?;
    service
        .git_release_delete_by_name(
            &session, user_id, &path.wk, &path.repo, path.id,
        )
        .await?;
    ok_empty()
}

#[utoipa::path(
    delete, path = "/api/v1/workspace/{wk}/repos/{repo}/releases/tags/{tag}",
    params(WkRepoPath, ("tag" = String, Path)),
    responses((status = 204)),
    security(("session" = []))
)]
pub async fn delete_release_by_tag(
    session: Session,
    service: web::Data<AppService>,
    path: web::Path<(String, String, String)>,
) -> Result<HttpResponse, ApiError> {
    let (wk, repo_name, tag) = path.into_inner();
    let user_id = session
        .user()
        .ok_or(ApiError(service::error::AppError::Unauthorized))?;
    service
        .git_release_delete_by_tag_name(
            &session, user_id, &wk, &repo_name, &tag,
        )
        .await?;
    ok_empty()
}
