import { NextRequest, NextResponse } from "next/server";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

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

export async function PATCH(req: NextRequest, { params }: Ctx) {
  try {
    const session = await getServerSession(authOptions);
    if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    const { id } = await params;

    const body = await req.json().catch(() => null);
    if (!body) return NextResponse.json({ error: "Invalid body" }, { status: 400 });

    const list = await prisma.list.findFirst({ where: { id, userId: session.user.id } });
    if (!list) return NextResponse.json({ error: "Not found" }, { status: 404 });

    const allowed = ["name", "color", "icon", "sortOrder"];
    const data: Record<string, unknown> = {};
    for (const key of allowed) {
      if (key in body) data[key] = body[key];
    }

    const updated = await prisma.list.update({ where: { id }, data });
    return NextResponse.json(updated);
  } catch (err) {
    console.error("[lists/id:PATCH]", err);
    return NextResponse.json({ error: "Failed to update list" }, { status: 500 });
  }
}

export async function DELETE(_: NextRequest, { params }: Ctx) {
  try {
    const session = await getServerSession(authOptions);
    if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    const { id } = await params;

    const list = await prisma.list.findFirst({ where: { id, userId: session.user.id } });
    if (!list) return NextResponse.json({ error: "Not found" }, { status: 404 });

    await prisma.list.delete({ where: { id } });
    return NextResponse.json({ ok: true });
  } catch (err) {
    console.error("[lists/id:DELETE]", err);
    return NextResponse.json({ error: "Failed to delete list" }, { status: 500 });
  }
}