import { NextRequest, NextResponse } from "next/server";
import { getTeamMember, updateTeamMember, deleteTeamMember } from "@/lib/db";
import { revalidatePath } from "next/cache";

type Params = { params: Promise<{ id: string }> };

function parseId(raw: string): number | null {
  const n = Number(raw);
  return Number.isInteger(n) && n > 0 ? n : null;
}

export async function GET(_request: NextRequest, { params }: Params) {
  const { id } = await params;
  const numId = parseId(id);
  if (!numId) {
    return NextResponse.json({ error: "Invalid ID" }, { status: 400 });
  }
  const member = getTeamMember(numId);
  if (!member) {
    return NextResponse.json({ error: "Not found" }, { status: 404 });
  }
  return NextResponse.json(member);
}

export async function PUT(request: NextRequest, { params }: Params) {
  const { id } = await params;
  const numId = parseId(id);
  if (!numId) {
    return NextResponse.json({ error: "Invalid ID" }, { status: 400 });
  }
  const data = await request.json();
  updateTeamMember(numId, data);
  revalidatePath("/");
  return NextResponse.json({ ok: true });
}

export async function DELETE(_request: NextRequest, { params }: Params) {
  const { id } = await params;
  const numId = parseId(id);
  if (!numId) {
    return NextResponse.json({ error: "Invalid ID" }, { status: 400 });
  }
  deleteTeamMember(numId);
  revalidatePath("/");
  return NextResponse.json({ ok: true });
}
