import { createKnowledgeEntry, listKnowledgeEntries } 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";

export async function GET(): Promise<Response> {
  const auth = await requirePermission("knowledge:read", {
    action: "ai.knowledge.list",
    targetType: "ai_knowledge",
  });
  if (!auth.success) {
    return auth.response;
  }

  const entries = await listKnowledgeEntries(auth.context);
  return jsonSuccess("知识库已加载", { entries });
}

export async function POST(request: Request): Promise<Response> {
  const auth = await requirePermission("knowledge:manage", {
    action: "ai.knowledge.create",
    targetType: "ai_knowledge",
  });
  if (!auth.success) {
    return auth.response;
  }

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

  const result = await createKnowledgeEntry(auth.context, 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.create",
    targetType: "ai_knowledge",
    targetId: result.data.entry.id,
    result: "success",
    reason: `创建知识库条目：${result.data.entry.title}`,
  });

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