import { fail, guard, ok, readJson } from "@/lib/api";
import { prisma } from "@/lib/db";
import { encrypt } from "@/lib/crypto";

export async function PATCH(req: Request, ctx: { params: Promise<{ id: string }> }) {
  const g = await guard(); if (g) return g;
  const { id } = await ctx.params;
  const b = await readJson<Record<string, unknown>>(req);
  const data: Record<string, unknown> = {};
  for (const k of ["name", "host", "port", "username", "authType", "notes"]) {
    if (b[k] !== undefined) data[k] = b[k];
  }
  if (typeof b.password === "string") {
    data.passwordEnc = b.password ? encrypt(b.password) : null;
  }
  if (typeof b.privateKey === "string") {
    data.privateKeyEnc = b.privateKey ? encrypt(b.privateKey) : null;
  }
  const h = await prisma.host.update({ where: { id }, data });
  return ok({ id: h.id });
}

export async function DELETE(_req: Request, ctx: { params: Promise<{ id: string }> }) {
  const g = await guard(); if (g) return g;
  const { id } = await ctx.params;
  const cnt = await prisma.agent.count({ where: { hostId: id } });
  if (cnt > 0) return fail("host_in_use", 409);
  await prisma.host.delete({ where: { id } });
  return ok({ ok: true });
}
