import { NextResponse } from "next/server";
import { z } from "zod";
import { prisma } from "@/lib/db";
import { requireAuth } from "@/lib/auth/middleware";
import { encrypt } from "@/lib/crypto/aes";

export async function GET(req: Request) {
  const auth = await requireAuth(req);
  if (!auth.ok) return NextResponse.json({ error: "unauthorized" }, { status: auth.status });
  const targets = await prisma.deployTarget.findMany({
    orderBy: { createdAt: "desc" },
    include: { _count: { select: { projects: true } } },
  });
  // strip authBlob from response
  const safe = targets.map(({ authBlob, ...rest }) => rest);
  return NextResponse.json({ targets: safe });
}

const Body = z.object({
  name: z.string().min(1).max(80),
  host: z.string().min(1),
  sshPort: z.number().int().min(1).max(65535).default(22),
  sshUser: z.string().default("root"),
  authMode: z.enum(["password", "key"]),
  password: z.string().optional(),
  privateKey: z.string().optional(),
  composePath: z.string().default("/opt/{name}/docker-compose.yml"),
  notes: z.string().optional(),
});

export async function POST(req: Request) {
  const auth = await requireAuth(req);
  if (!auth.ok) return NextResponse.json({ error: "unauthorized" }, { status: auth.status });

  let parsed;
  try { parsed = Body.safeParse(await req.json()); }
  catch { return NextResponse.json({ error: "invalid_json" }, { status: 400 }); }
  if (!parsed.success) return NextResponse.json({ error: "invalid_body", details: parsed.error.format() }, { status: 400 });

  const { authMode, password, privateKey, ...rest } = parsed.data;
  if (authMode === "password" && !password) return NextResponse.json({ error: "password_required" }, { status: 400 });
  if (authMode === "key" && !privateKey) return NextResponse.json({ error: "privateKey_required" }, { status: 400 });

  const dup = await prisma.deployTarget.findUnique({ where: { name: rest.name } });
  if (dup) return NextResponse.json({ error: "duplicate_name" }, { status: 409 });

  const authBlob = encrypt(JSON.stringify({ password, privateKey }));
  const target = await prisma.deployTarget.create({
    data: { ...rest, authMode, authBlob },
  });
  const { authBlob: _, ...safe } = target;
  return NextResponse.json({ target: safe }, { status: 201 });
}
