import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireRole } from "@/lib/auth";
import { generateApiKey } from "@/lib/device-punch";

export async function PUT(req: Request, ctx: { params: Promise<{ id: string }> }) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session?.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const { id } = await ctx.params;
  const machine = await prisma.attendanceMachine.findFirst({
    where: { id: Number(id), institutionId: session.institutionId },
  });
  if (!machine) return NextResponse.json({ error: "Not found" }, { status: 404 });

  const body = (await req.json().catch(() => ({}))) as Record<string, unknown>;
  const str = (v: unknown) => (typeof v === "string" ? v.trim() : "");
  const data: Record<string, unknown> = {};
  if (body.name !== undefined && str(body.name)) data.name = str(body.name);
  if (typeof body.brand === "string") data.brand = body.brand;
  if (typeof body.mode === "string") data.mode = body.mode;
  if (body.hasCard !== undefined) data.hasCard = body.hasCard !== false;
  if (body.hasFinger !== undefined) data.hasFinger = body.hasFinger === true;
  if (body.hasFace !== undefined) data.hasFace = body.hasFace === true;
  if (body.ipAddress !== undefined) data.ipAddress = str(body.ipAddress) || null;
  if (body.port !== undefined) data.port = Number(body.port) || 4370;
  if (body.serialNumber !== undefined) data.serialNumber = str(body.serialNumber) || null;
  if (body.location !== undefined) data.location = str(body.location) || null;
  if (body.pollMinutes !== undefined) data.pollMinutes = Number(body.pollMinutes) || null;
  if (body.isActive !== undefined) data.isActive = body.isActive !== false;
  if (body.note !== undefined) data.note = str(body.note) || null;
  if (body.regenerateKey === true) data.apiKey = generateApiKey();

  const updated = await prisma.attendanceMachine.update({ where: { id: machine.id }, data });
  return NextResponse.json({ machine: updated });
}

export async function DELETE(_req: Request, ctx: { params: Promise<{ id: string }> }) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session?.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
  const { id } = await ctx.params;
  const machine = await prisma.attendanceMachine.findFirst({
    where: { id: Number(id), institutionId: session.institutionId },
  });
  if (!machine) return NextResponse.json({ error: "Not found" }, { status: 404 });
  await prisma.attendanceMachine.delete({ where: { id: machine.id } });
  return NextResponse.json({ ok: true });
}
