use super::PageQuery;
use crate::{ApiResponse, error::ApiError};
use actix_web::{HttpResponse, Result, web};
use service::AppService;
use session::Session;

#[utoipa::path(
    get,
    path = "/api/projects/{project_name}/members",
    params(
        ("project_name" = String, Path),
        ("page" = Option<u64>, Query),
        ("per_page" = Option<u64>, Query),
    ),
    responses(
        (status = 200, description = "List project members", body = ApiResponse<service::project::members::MemberListResponse>),
        (status = 401, description = "Unauthorized"),
        (status = 404, description = "Not found"),
),
    tag = "Project"
)]
pub async fn project_members(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<String>,
    query: web::Query<PageQuery>,
) -> Result<HttpResponse, ApiError> {
    let project_name = path.into_inner();
    let resp = service
        .project_get_members(project_name, query.page, query.per_page, &session)
        .await?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[utoipa::path(
    patch,
    path = "/api/projects/{project_name}/members/role",
    params(("project_name" = String, Path)),
    request_body = service::project::members::UpdateMemberRoleRequest,
    responses(
        (status = 200, description = "Update member role"),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Forbidden"),
        (status = 404, description = "Not found"),
),
    tag = "Project"
)]
pub async fn project_update_member_role(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<String>,
    body: web::Json<service::project::members::UpdateMemberRoleRequest>,
) -> Result<HttpResponse, ApiError> {
    let project_name = path.into_inner();
    service
        .project_update_member_role(project_name, body.into_inner(), &session)
        .await?;
    Ok(ApiResponse::ok(serde_json::json!({ "success": true })).to_response())
}

#[utoipa::path(
    delete,
    path = "/api/projects/{project_name}/members/{user_id}",
    params(
        ("project_name" = String, Path),
        ("user_id" = String, Path),
    ),
    responses(
        (status = 200, description = "Remove member from project"),
        (status = 401, description = "Unauthorized"),
        (status = 403, description = "Forbidden"),
        (status = 404, description = "Not found"),
),
    tag = "Project"
)]
pub async fn project_remove_member(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<(String, String)>,
) -> Result<HttpResponse, ApiError> {
    let (project_name, user_id) = path.into_inner();
    let user_uuid = uuid::Uuid::parse_str(&user_id)
        .map_err(|_| service::error::AppError::BadRequest("Invalid UUID".to_string()))?;
    service
        .project_remove_member(project_name, user_uuid, &session)
        .await?;
    Ok(ApiResponse::ok(serde_json::json!({ "success": true })).to_response())
}
