use axum::Extension;
use axum::extract::{FromRef, Path, Query, State};
use axum::response::Json;
use validator::Validate;

use erp_core::error::AppError;
use erp_core::rbac::require_permission;
use erp_core::types::{ApiResponse, PaginatedResponse, Pagination, TenantContext};
use uuid::Uuid;

use crate::dto::{CompleteTaskReq, DelegateTaskReq, TaskResp};
use crate::service::task_service::TaskService;
use crate::workflow_state::WorkflowState;

#[utoipa::path(
    get,
    path = "/api/v1/workflow/tasks/pending",
    params(Pagination),
    responses(
        (status = 200, description = "成功", body = ApiResponse<PaginatedResponse<TaskResp>>),
        (status = 401, description = "未授权"),
        (status = 403, description = "权限不足"),
    ),
    security(("bearer_auth" = [])),
    tag = "流程任务"
)]
/// GET /api/v1/workflow/tasks/pending
pub async fn list_pending_tasks<S>(
    State(state): State<WorkflowState>,
    Extension(ctx): Extension<TenantContext>,
    Query(pagination): Query<Pagination>,
) -> Result<Json<ApiResponse<PaginatedResponse<TaskResp>>>, AppError>
where
    WorkflowState: FromRef<S>,
    S: Clone + Send + Sync + 'static,
{
    require_permission(&ctx, "workflow.approve")?;

    let (tasks, total) =
        TaskService::list_pending(ctx.tenant_id, ctx.user_id, &pagination, &state.db).await?;

    let page = pagination.page.unwrap_or(1);
    let page_size = pagination.limit();
    let total_pages = total.div_ceil(page_size);

    Ok(Json(ApiResponse::ok(PaginatedResponse {
        data: tasks,
        total,
        page,
        page_size,
        total_pages,
    })))
}

#[utoipa::path(
    get,
    path = "/api/v1/workflow/tasks/completed",
    params(Pagination),
    responses(
        (status = 200, description = "成功", body = ApiResponse<PaginatedResponse<TaskResp>>),
        (status = 401, description = "未授权"),
        (status = 403, description = "权限不足"),
    ),
    security(("bearer_auth" = [])),
    tag = "流程任务"
)]
/// GET /api/v1/workflow/tasks/completed
pub async fn list_completed_tasks<S>(
    State(state): State<WorkflowState>,
    Extension(ctx): Extension<TenantContext>,
    Query(pagination): Query<Pagination>,
) -> Result<Json<ApiResponse<PaginatedResponse<TaskResp>>>, AppError>
where
    WorkflowState: FromRef<S>,
    S: Clone + Send + Sync + 'static,
{
    require_permission(&ctx, "workflow.approve")?;

    let (tasks, total) =
        TaskService::list_completed(ctx.tenant_id, ctx.user_id, &pagination, &state.db).await?;

    let page = pagination.page.unwrap_or(1);
    let page_size = pagination.limit();
    let total_pages = total.div_ceil(page_size);

    Ok(Json(ApiResponse::ok(PaginatedResponse {
        data: tasks,
        total,
        page,
        page_size,
        total_pages,
    })))
}

#[utoipa::path(
    post,
    path = "/api/v1/workflow/tasks/{id}/complete",
    params(("id" = Uuid, Path, description = "任务ID")),
    request_body = CompleteTaskReq,
    responses(
        (status = 200, description = "成功", body = ApiResponse<TaskResp>),
        (status = 401, description = "未授权"),
        (status = 403, description = "权限不足"),
        (status = 404, description = "任务不存在"),
    ),
    security(("bearer_auth" = [])),
    tag = "流程任务"
)]
/// POST /api/v1/workflow/tasks/{id}/complete
pub async fn complete_task<S>(
    State(state): State<WorkflowState>,
    Extension(ctx): Extension<TenantContext>,
    Path(id): Path<Uuid>,
    Json(req): Json<CompleteTaskReq>,
) -> Result<Json<ApiResponse<TaskResp>>, AppError>
where
    WorkflowState: FromRef<S>,
    S: Clone + Send + Sync + 'static,
{
    require_permission(&ctx, "workflow.approve")?;
    req.validate()
        .map_err(|e| AppError::Validation(e.to_string()))?;

    let resp = TaskService::complete(
        id,
        ctx.tenant_id,
        ctx.user_id,
        &req,
        &state.db,
        &state.event_bus,
    )
    .await?;

    Ok(Json(ApiResponse::ok(resp)))
}

#[utoipa::path(
    post,
    path = "/api/v1/workflow/tasks/{id}/delegate",
    params(("id" = Uuid, Path, description = "任务ID")),
    request_body = DelegateTaskReq,
    responses(
        (status = 200, description = "成功", body = ApiResponse<TaskResp>),
        (status = 401, description = "未授权"),
        (status = 403, description = "权限不足"),
        (status = 404, description = "任务不存在"),
    ),
    security(("bearer_auth" = [])),
    tag = "流程任务"
)]
/// POST /api/v1/workflow/tasks/{id}/delegate
pub async fn delegate_task<S>(
    State(state): State<WorkflowState>,
    Extension(ctx): Extension<TenantContext>,
    Path(id): Path<Uuid>,
    Json(req): Json<DelegateTaskReq>,
) -> Result<Json<ApiResponse<TaskResp>>, AppError>
where
    WorkflowState: FromRef<S>,
    S: Clone + Send + Sync + 'static,
{
    require_permission(&ctx, "workflow.delegate")?;
    req.validate()
        .map_err(|e| AppError::Validation(e.to_string()))?;

    let resp = TaskService::delegate(id, ctx.tenant_id, ctx.user_id, &req, &state.db).await?;

    Ok(Json(ApiResponse::ok(resp)))
}

#[utoipa::path(
    put,
    path = "/api/v1/workflow/tasks/{id}/claim",
    params(("id" = Uuid, Path, description = "任务ID")),
    responses(
        (status = 200, description = "认领成功", body = ApiResponse<TaskResp>),
        (status = 401, description = "未授权"),
        (status = 403, description = "权限不足"),
        (status = 404, description = "任务不存在"),
    ),
    security(("bearer_auth" = [])),
    tag = "流程任务"
)]
/// PUT /api/v1/workflow/tasks/{id}/claim
pub async fn claim_task<S>(
    State(state): State<WorkflowState>,
    Extension(ctx): Extension<TenantContext>,
    Path(id): Path<Uuid>,
) -> Result<Json<ApiResponse<TaskResp>>, AppError>
where
    WorkflowState: FromRef<S>,
    S: Clone + Send + Sync + 'static,
{
    require_permission(&ctx, "workflow.approve")?;

    let resp = TaskService::claim(id, ctx.tenant_id, ctx.user_id, &state.db).await?;

    Ok(Json(ApiResponse::ok(resp)))
}
