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}/audit-logs",
    params(
        ("project_name" = String, Path),
        ("page" = Option<u64>, Query),
        ("per_page" = Option<u64>, Query),
    ),
    responses(
        (status = 200, description = "List project audit logs", body = ApiResponse<Vec<service::project::audit::AuditLogResponse>>),
        (status = 401, description = "Unauthorized"),
        (status = 404, description = "Not found"),
),
    tag = "Project"
)]
pub async fn project_audit_logs(
    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_audit_logs(project_name, query.page, query.per_page, &session)
        .await?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[utoipa::path(
    get,
    path = "/api/projects/{project_name}/audit-logs/{log_id}",
    params(
        ("project_name" = String, Path),
        ("log_id" = i64, Path),
    ),
    responses(
        (status = 200, description = "Get project audit log", body = ApiResponse<service::project::audit::AuditLogResponse>),
        (status = 401, description = "Unauthorized"),
        (status = 404, description = "Not found"),
),
    tag = "Project"
)]
pub async fn project_audit_log(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<(String, i64)>,
) -> Result<HttpResponse, ApiError> {
    let (_project_name, log_id) = path.into_inner();
    let resp = service.project_get_audit_log(log_id, &session).await?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[utoipa::path(
    post,
    path = "/api/projects/{project_name}/audit-logs",
    params(("project_name" = String, Path)),
    request_body = service::project::audit::AuditLogParams,
    responses(
        (status = 200, description = "Log project audit event", body = ApiResponse<service::project::audit::AuditLogResponse>),
        (status = 401, description = "Unauthorized"),
        (status = 404, description = "Not found"),
),
    tag = "Project"
)]
pub async fn project_log_audit(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<String>,
    body: web::Json<service::project::audit::AuditLogParams>,
) -> Result<HttpResponse, ApiError> {
    let project_name = path.into_inner();
    let resp = service
        .project_log_audit(project_name, body.into_inner(), &session)
        .await?;
    Ok(ApiResponse::ok(resp).to_response())
}
