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

export async function GET(_req: Request, ctx: { params: Promise<{ id: string }> }) {
  const g = await guard(); if (g) return g;
  const { id } = await ctx.params;
  const a = await prisma.agent.findUnique({
    where: { id },
    include: {
      host: true,
      events: { orderBy: { createdAt: "desc" }, take: 30 },
    },
  });
  if (!a) return fail("not_found", 404);
  return ok({ agent: a });
}

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 ["displayName", "installPath", "configJson", "notes", "autoStart", "port", "deployMethod", "deployRef"]) {
    if (b[k] !== undefined) data[k] = b[k];
  }
  const a = await prisma.agent.update({ where: { id }, data });
  return ok({ id: a.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;
  // Cố gắng uninstall trước khi xoá row (không bắt buộc thành công).
  try { await runAction(id, "uninstall"); } catch {}
  await prisma.agent.delete({ where: { id } });
  return ok({ ok: true });
}
