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

    const task = await prisma.task.findFirst({
      where: { id, userId: session.user.id },
      include: { children: { orderBy: { sortOrder: "asc" } }, tags: { include: { tag: true } } },
    });
    if (!task) return NextResponse.json({ error: "Not found" }, { status: 404 });
    return NextResponse.json(task);
  } catch (err) {
    console.error("[tasks/id:GET]", err);
    return NextResponse.json({ error: "Failed to fetch task" }, { status: 500 });
  }
}

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 task = await prisma.task.findFirst({ where: { id, userId: session.user.id } });
    if (!task) return NextResponse.json({ error: "Not found" }, { status: 404 });

    // Sanitize allowed fields
    const allowed = ["title", "note", "completed", "completedAt", "dueDate", "priority", "sortOrder", "listId"];
    const data: Record<string, unknown> = {};
    for (const key of allowed) {
      if (key in body) data[key] = body[key];
    }

    // Auto-set completedAt
    if ("completed" in data) {
      data.completedAt = data.completed ? new Date() : null;
    }
    // Convert dueDate string to Date
    if ("dueDate" in data) {
      data.dueDate = data.dueDate ? new Date(data.dueDate as string) : null;
    }

    const updated = await prisma.task.update({
      where: { id },
      data,
      include: { children: { orderBy: { sortOrder: "asc" } }, tags: { include: { tag: true } } },
    });
    return NextResponse.json(updated);
  } catch (err) {
    console.error("[tasks/id:PATCH]", err);
    return NextResponse.json({ error: "Failed to update task" }, { 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 task = await prisma.task.findFirst({ where: { id, userId: session.user.id } });
    if (!task) return NextResponse.json({ error: "Not found" }, { status: 404 });

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