import { NextResponse } from "next/server";
import { getSessionPayload } from "@/lib/auth/session";
import { applyAiSuggestionDecision } from "@/lib/ai/suggestions";

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

function parseDecision(value: unknown) {
  return value === "accept" || value === "dismiss" ? value : null;
}

export async function POST(request: Request, context: RouteContext) {
  const session = await getSessionPayload();

  if (!session) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { id } = await context.params;
  const body = (await request.json().catch(() => ({}))) as Record<string, unknown>;
  const decision = parseDecision(body.decision);

  if (!id || !decision) {
    return NextResponse.json({ error: "Decision invalida." }, { status: 400 });
  }

  const updated = await applyAiSuggestionDecision(session.userId, id, decision);

  if (!updated) {
    return NextResponse.json({ error: "Sugerencia no encontrada." }, { status: 404 });
  }

  return NextResponse.json({ ok: true, suggestion: updated });
}
