import { NextRequest, NextResponse } from "next/server";
import { addTaskToGantt, parseTaskInput } from "@/lib/server/taskParser";

export async function POST(req: NextRequest) {
  try {
    const { text } = await req.json();
    
    if (!text || typeof text !== "string") {
      return NextResponse.json({ error: "Missing text" }, { status: 400 });
    }
    
    const result = await addTaskToGantt(text);
    
    if (!result.success) {
      return NextResponse.json({ error: result.error }, { status: 500 });
    }
    
    const parsed = parseTaskInput(text);
    
    return NextResponse.json({
      success: true,
      task: result.task,
      parsed: {
        title: parsed.title,
        assignee: parsed.assigneeId === "0a3e400c-3932-48ae-9b65-f3f9c6f26fe9" ? "Matt" : "Max",
        priority: parsed.priority,
        dueDate: parsed.dueDate,
      },
    });
  } catch (err: unknown) {
    console.error("Error parsing task:", err);
    const message = err instanceof Error ? err.message : "Unknown error";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
