import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
import { recordAuditLog } from "@/modules/core/server/audit";
import { requirePermission } from "@/modules/core/server/auth";
import { isCareMutationFailure, updateCareTaskStatus } from "@/modules/care/server/operations";
import { validateCareTaskStatusUpdateInput } from "@/modules/care/types";

type RouteContext = {
  params: Promise<{
    id: string;
  }>;
};

export async function PATCH(request: Request, context: RouteContext): Promise<Response> {
  const { id } = await context.params;
  const auth = await requirePermission("care:manage", {
    action: "care.task.update",
    targetType: "care_task",
    targetId: id,
  });

  if (!auth.success) {
    return auth.response;
  }

  const organizationId = auth.context.organization?.id;
  if (!organizationId) {
    return jsonFailure("请选择机构后处理护理任务", 400);
  }

  const input = validateCareTaskStatusUpdateInput(await readJsonBody(request));
  if (!input.success) {
    return jsonFailure(input.reason);
  }

  const task = await updateCareTaskStatus({
    ...input.data,
    id,
    organizationId,
    accountId: auth.context.account.id,
  });
  if (isCareMutationFailure(task)) {
    return jsonFailure(task.reason, task.status);
  }

  await recordAuditLog({
    actor: auth.context.account,
    organizationId,
    action: "care.task.update",
    targetType: "care_task",
    targetId: task.id,
    result: "success",
    reason: `处理护理任务：${task.title}`,
  });

  return jsonSuccess("护理任务已更新", { task });
}
