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

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

    const lists = await prisma.list.findMany({
      where: { userId: session.user.id },
      orderBy: { sortOrder: "asc" },
      include: {
        _count: { select: { tasks: { where: { completed: false, parentId: null } } } },
      },
    });
    return NextResponse.json(lists);
  } catch (err) {
    console.error("[lists:GET]", err);
    return NextResponse.json({ error: "Failed to fetch lists" }, { status: 500 });
  }
}

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

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

    const { name, color, icon } = body;
    if (!name?.trim()) return NextResponse.json({ error: "Name required" }, { status: 400 });

    const count = await prisma.list.count({ where: { userId: session.user.id } });
    const list = await prisma.list.create({
      data: {
        userId: session.user.id,
        name: name.trim(),
        color: color || "#4B7BF5",
        icon: icon || "list",
        sortOrder: count,
      },
    });
    return NextResponse.json(list, { status: 201 });
  } catch (err) {
    console.error("[lists:POST]", err);
    return NextResponse.json({ error: "Failed to create list" }, { status: 500 });
  }
}