import { fail, guard, ok, readJson } from "@/lib/api";
import { prisma } from "@/lib/db";
import { AGENT_KINDS, type AgentKind } from "@/lib/agents";

type Item = {
  name: string;
  kind: string;
  deployMethod: string;
  deployRef: string;
};

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 body = await readJson<{ items?: Item[] }>(req);
  if (!body.items || !Array.isArray(body.items) || body.items.length === 0) {
    return fail("no_items");
  }

  const created: { id: string; name: string }[] = [];
  const skipped: { ref: string; reason: string }[] = [];

  for (const it of body.items) {
    if (!it.name || !it.kind || !it.deployMethod || !it.deployRef) {
      skipped.push({ ref: `${it.deployMethod}:${it.deployRef}`, reason: "missing_fields" });
      continue;
    }
    if (!AGENT_KINDS.includes(it.kind as AgentKind)) {
      skipped.push({ ref: `${it.deployMethod}:${it.deployRef}`, reason: "invalid_kind" });
      continue;
    }
    if (!["systemd", "docker", "pm2", "manual"].includes(it.deployMethod)) {
      skipped.push({ ref: `${it.deployMethod}:${it.deployRef}`, reason: "invalid_method" });
      continue;
    }
    // Sanitize name: agent name unique trong DB; nếu trùng thì append host short id.
    let safeName = it.name.replace(/[^a-zA-Z0-9_-]/g, "-").slice(0, 40);
    if (!/^[a-zA-Z0-9_-]{2,40}$/.test(safeName)) safeName = `agent-${Date.now()}`;
    const exists = await prisma.agent.findUnique({ where: { name: safeName } });
    if (exists) safeName = `${safeName}-${host.id.slice(-4)}`.slice(0, 40);

    try {
      const a = await prisma.agent.create({
        data: {
          name: safeName,
          kind: it.kind,
          hostId: id,
          declared: true,
          deployMethod: it.deployMethod,
          deployRef: it.deployRef,
          status: "declared",
          notes: "Đã import từ scan host.",
        },
      });
      created.push({ id: a.id, name: a.name });
    } catch (e: unknown) {
      skipped.push({ ref: `${it.deployMethod}:${it.deployRef}`, reason: e instanceof Error ? e.message : "create_failed" });
    }
  }

  return ok({ created, skipped });
}
