import { fail, guard, ok } from "@/lib/api";
import { prisma } from "@/lib/db";
import { scanHost } from "@/lib/deploy/scan";

export async function POST(_req: Request, ctx: { params: Promise<{ id: string }> }) {
  const g = await guard(); if (g) return g;
  const { id } = await ctx.params;
  const host = await prisma.host.findUnique({ where: { id } });
  if (!host) return fail("not_found", 404);

  const result = await scanHost(id);

  // Mark candidate đã được khai báo trong AM
  const existing = await prisma.agent.findMany({
    where: { hostId: id },
    select: { deployMethod: true, deployRef: true, name: true },
  });
  const seen = new Set(existing.map((a) => `${a.deployMethod}:${a.deployRef}`));
  for (const c of result.candidates) {
    if (seen.has(`${c.deployMethod}:${c.deployRef}`)) c.alreadyImported = true;
  }

  return ok(result);
}
