import { generateElderAiAnalysis, listElderAiAnalyses } from "@/modules/ai/server/analysis";
import { jsonFailure, jsonSuccess } from "@/modules/core/server/api";
import { requirePermission } from "@/modules/core/server/auth";

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

async function requireAiAnalysisAccess(id: string) {
  const aiAuth = await requirePermission("ai:read", {
    action: "ai.elder_analysis.access",
    targetType: "elder",
    targetId: id,
  });
  if (!aiAuth.success) {
    return aiAuth;
  }

  const elderAuth = await requirePermission("elder:read", {
    action: "ai.elder_analysis.access",
    targetType: "elder",
    targetId: id,
    organizationId: aiAuth.context.organization?.id,
  });
  if (!elderAuth.success) {
    return elderAuth;
  }

  return aiAuth;
}

export async function GET(_request: Request, context: RouteContext): Promise<Response> {
  const { id } = await context.params;
  const auth = await requireAiAnalysisAccess(id);
  if (!auth.success) {
    return auth.response;
  }

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

  return jsonSuccess("AI 分析历史已加载", { history: result.data.history });
}

export async function POST(_request: Request, context: RouteContext): Promise<Response> {
  const { id } = await context.params;
  const auth = await requireAiAnalysisAccess(id);
  if (!auth.success) {
    return auth.response;
  }

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

  return jsonSuccess("AI 分析已生成", { analysis: result.data.analysis }, 201);
}
