import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
import { recordAuditLog } from "@/modules/core/server/audit";
import { requirePermission } from "@/modules/core/server/auth";
import { deleteFamilyFeedback, isFamilyMutationFailure, updateFamilyFeedback } from "@/modules/family/server/operations";
import { validateFamilyFeedbackInput } from "@/modules/family/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("family:manage", { action: "family.feedback.update", targetType: "family_feedback", targetId: id });
  if (!auth.success) {
    return auth.response;
  }

  const organizationId = auth.context.organization?.id;
  if (!organizationId) {
    return jsonFailure("请选择机构后维护家属反馈", 400);
  }

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

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

  await recordAuditLog({
    actor: auth.context.account,
    organizationId,
    action: "family.feedback.update",
    targetType: "family_feedback",
    targetId: feedback.id,
    result: "success",
    reason: `更新家属反馈：${feedback.elderName}`,
  });

  return jsonSuccess("家属反馈已更新", { feedback });
}

export async function DELETE(_request: Request, context: RouteContext): Promise<Response> {
  const { id } = await context.params;
  const auth = await requirePermission("family:manage", { action: "family.feedback.delete", targetType: "family_feedback", targetId: id });
  if (!auth.success) {
    return auth.response;
  }

  const organizationId = auth.context.organization?.id;
  if (!organizationId) {
    return jsonFailure("请选择机构后维护家属反馈", 400);
  }

  const feedback = await deleteFamilyFeedback({ id, organizationId });
  if (isFamilyMutationFailure(feedback)) {
    return jsonFailure(feedback.reason, feedback.status);
  }

  await recordAuditLog({
    actor: auth.context.account,
    organizationId,
    action: "family.feedback.delete",
    targetType: "family_feedback",
    targetId: feedback.id,
    result: "success",
    reason: `删除家属反馈：${feedback.elderName}`,
  });

  return jsonSuccess("家属反馈已删除", { feedback });
}
