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(req: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    if (!session) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

    const { searchParams } = new URL(req.url);
    const listId = searchParams.get("listId");
    const showCompleted = searchParams.get("showCompleted") === "true";

    const where: Record<string, unknown> = {
      userId: session.user.id,
      parentId: null,
      ...(listId ? { listId } : {}),
      ...(showCompleted ? {} : { completed: false }),
    };

    const tasks = await prisma.task.findMany({
      where,
      orderBy: [{ sortOrder: "asc" }, { createdAt: "asc" }],
      include: {
        children: { orderBy: [{ sortOrder: "asc" }] },
        tags: { include: { tag: true } },
      },
    });
    return NextResponse.json(tasks);
  } catch (err) {
    console.error("[tasks:GET]", err);
    return NextResponse.json({ error: "Failed to fetch tasks" }, { 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 { title, listId, parentId, dueDate, priority, note } = body;
    if (!title || !listId) return NextResponse.json({ error: "title and listId required" }, { status: 400 });

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

    const count = await prisma.task.count({ where: { listId, parentId: parentId || null } });
    const task = await prisma.task.create({
      data: {
        userId: session.user.id,
        listId,
        parentId: parentId || null,
        title: title.trim(),
        note: note?.trim() || null,
        dueDate: dueDate ? new Date(dueDate) : null,
        priority: Number(priority) || 0,
        sortOrder: count,
      },
      include: { children: true, tags: { include: { tag: true } } },
    });
    return NextResponse.json(task, { status: 201 });
  } catch (err) {
    console.error("[tasks:POST]", err);
    return NextResponse.json({ error: "Failed to create task" }, { status: 500 });
  }
}