import { deleteKnowledgeEntry, updateKnowledgeEntry } from "@/modules/ai/server/knowledge";
import { validateKnowledgeEntryInput } from "@/modules/ai/types";
import { jsonFailure, jsonSuccess, readJsonBody } from "@/modules/core/server/api";
import { recordAuditLog } from "@/modules/core/server/audit";
import { requirePermission } from "@/modules/core/server/auth";

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("knowledge:manage", {
    action: "ai.knowledge.update",
    targetType: "ai_knowledge",
    targetId: id,
  });
  if (!auth.success) {
    return auth.response;
  }

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

  const result = await updateKnowledgeEntry(auth.context, id, input.input);
  if (!result.success) {
    return jsonFailure(result.reason, result.status);
  }

  await recordAuditLog({
    actor: auth.context.account,
    organizationId: result.data.entry.organizationId ?? auth.context.organization?.id,
    action: "ai.knowledge.update",
    targetType: "ai_knowledge",
    targetId: result.data.entry.id,
    result: "success",
    reason: `更新知识库条目：${result.data.entry.title}`,
  });

  return jsonSuccess("知识库条目已更新", { entry: result.data.entry });
}

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

  const result = await deleteKnowledgeEntry(auth.context, id);
  if (!result.success) {
    return jsonFailure(result.reason, result.status);
  }

  await recordAuditLog({
    actor: auth.context.account,
    organizationId: result.data.entry.organizationId ?? auth.context.organization?.id,
    action: "ai.knowledge.delete",
    targetType: "ai_knowledge",
    targetId: result.data.entry.id,
    result: "success",
    reason: `删除知识库条目：${result.data.entry.title}`,
  });

  return jsonSuccess("知识库条目已删除", { entry: result.data.entry });
}
