use crate::{ApiResponse, error::ApiError};
use actix_web::{HttpResponse, Result, web};
use service::AppService;
use service::git::watch::{GitWatchRequest, WatchCountResponse, WatchUserListResponse};
use session::Session;

#[derive(serde::Deserialize, utoipa::IntoParams)]
pub struct WatchPagerQuery {
    pub page: Option<i64>,
    pub par_page: Option<i64>,
}

impl From<WatchPagerQuery> for service::Pager {
    fn from(q: WatchPagerQuery) -> Self {
        service::Pager {
            page: q.page.unwrap_or(1),
            par_page: q.par_page.unwrap_or(20),
        }
    }
}

#[utoipa::path(
    post,
    path = "/api/repos/{namespace}/{repo}/git/watch",
    params(
        ("namespace" = String, Path, description = "Project namespace"),
        ("repo" = String, Path, description = "Repository name"),
    ),
    request_body = GitWatchRequest,
    responses(
        (status = 401, description = "Unauthorized", body = ApiResponse<ApiError>),
        (status = 200, description = "Watch the repository"),
        (status = 404, description = "Not found", body = ApiResponse<ApiError>),
    ),
    tag = "Git"
)]
pub async fn git_watch(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<(String, String)>,
    body: web::Json<GitWatchRequest>,
) -> Result<HttpResponse, ApiError> {
    let (namespace, repo_name) = path.into_inner();
    service
        .git_watch(namespace, repo_name, body.into_inner(), &session)
        .await?;
    Ok(crate::api_success())
}

#[utoipa::path(
    delete,
    path = "/api/repos/{namespace}/{repo}/git/watch",
    params(
        ("namespace" = String, Path, description = "Project namespace"),
        ("repo" = String, Path, description = "Repository name"),
    ),
    responses(
        (status = 401, description = "Unauthorized", body = ApiResponse<ApiError>),
        (status = 200, description = "Unwatch the repository"),
        (status = 404, description = "Not found", body = ApiResponse<ApiError>),
    ),
    tag = "Git"
)]
pub async fn git_unwatch(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<(String, String)>,
) -> Result<HttpResponse, ApiError> {
    let (namespace, repo_name) = path.into_inner();
    service.git_unwatch(namespace, repo_name, &session).await?;
    Ok(crate::api_success())
}

#[utoipa::path(
    get,
    path = "/api/repos/{namespace}/{repo}/git/watch/is-watched",
    params(
        ("namespace" = String, Path, description = "Project namespace"),
        ("repo" = String, Path, description = "Repository name"),
    ),
    responses(
        (status = 401, description = "Unauthorized", body = ApiResponse<ApiError>),
        (status = 200, description = "Check if the current user is watching the repository", body = ApiResponse<serde_json::Value>),
        (status = 404, description = "Not found", body = ApiResponse<ApiError>),
    ),
    tag = "Git"
)]
pub async fn git_is_watched(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<(String, String)>,
) -> Result<HttpResponse, ApiError> {
    let (namespace, repo_name) = path.into_inner();
    let resp = service
        .git_is_watched(namespace, repo_name, &session)
        .await?;
    Ok(ApiResponse::ok(serde_json::json!({"is_watched": resp})).to_response())
}

#[utoipa::path(
    get,
    path = "/api/repos/{namespace}/{repo}/git/watch/count",
    params(
        ("namespace" = String, Path, description = "Project namespace"),
        ("repo" = String, Path, description = "Repository name"),
    ),
    responses(
        (status = 401, description = "Unauthorized", body = ApiResponse<ApiError>),
        (status = 200, description = "Get watch count for the repository", body = ApiResponse<WatchCountResponse>),
        (status = 404, description = "Not found", body = ApiResponse<ApiError>),
    ),
    tag = "Git"
)]
pub async fn git_watch_count(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<(String, String)>,
) -> Result<HttpResponse, ApiError> {
    let (namespace, repo_name) = path.into_inner();
    let resp = service
        .git_watch_count(namespace, repo_name, &session)
        .await?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[utoipa::path(
    get,
    path = "/api/repos/{namespace}/{repo}/git/watch/users",
    params(
        ("namespace" = String, Path, description = "Project namespace"),
        ("repo" = String, Path, description = "Repository name"),
        ("page" = Option<i64>, Query, description = "Page number"),
        ("per_page" = Option<i64>, Query, description = "Items per page"),
    ),
    responses(
        (status = 401, description = "Unauthorized", body = ApiResponse<ApiError>),
        (status = 200, description = "List users who are watching the repository", body = ApiResponse<WatchUserListResponse>),
        (status = 404, description = "Not found", body = ApiResponse<ApiError>),
    ),
    tag = "Git"
)]
pub async fn git_watch_user_list(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<(String, String)>,
    query: web::Query<WatchPagerQuery>,
) -> Result<HttpResponse, ApiError> {
    let (namespace, repo_name) = path.into_inner();
    let resp = service
        .git_watch_user_list(namespace, repo_name, query.into_inner().into(), &session)
        .await?;
    Ok(ApiResponse::ok(resp).to_response())
}
