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

export async function GET() {
  const g = await guard(); if (g) return g;
  const hosts = await prisma.host.findMany({
    orderBy: { createdAt: "desc" },
    include: { _count: { select: { agents: true } } },
  });
  return ok({
    hosts: hosts.map((h) => ({
      id: h.id,
      name: h.name,
      host: h.host,
      port: h.port,
      username: h.username,
      authType: h.authType,
      hasPassword: !!h.passwordEnc,
      hasKey: !!h.privateKeyEnc,
      notes: h.notes,
      lastSeenAt: h.lastSeenAt,
      agents: h._count.agents,
      createdAt: h.createdAt,
    })),
  });
}

type Body = {
  name?: string;
  host?: string;
  port?: number;
  username?: string;
  authType?: "password" | "key";
  password?: string;
  privateKey?: string;
  notes?: string;
};

export async function POST(req: Request) {
  const g = await guard(); if (g) return g;
  const b = await readJson<Body>(req);
  if (!b.name || !b.host) return fail("name_and_host_required");
  const h = await prisma.host.create({
    data: {
      name: b.name,
      host: b.host,
      port: b.port ?? 22,
      username: b.username ?? "root",
      authType: b.authType ?? "password",
      passwordEnc: b.password ? encrypt(b.password) : null,
      privateKeyEnc: b.privateKey ? encrypt(b.privateKey) : null,
      notes: b.notes ?? null,
    },
  });
  return ok({ id: h.id }, 201);
}
