import { NextRequest, NextResponse } from "next/server"; import { eq, sql } from "drizzle-orm"; import { db } from "@/lib/db"; import { claws, tasks } from "@/lib/db/schema"; import { incrementGlobalStat, incrementHourlyActivity, publishEvent, } from "@/lib/redis"; import { validateApiKey } from "@/lib/auth/api-key"; import { taskSchema } from "@/lib/validators/schemas"; export async function POST(req: NextRequest) { try { const authHeader = req.headers.get("authorization"); if (!authHeader?.startsWith("Bearer ")) { return NextResponse.json( { error: "Missing or invalid authorization header" }, { status: 401 } ); } const apiKey = authHeader.slice(7); const claw = await validateApiKey(apiKey); if (!claw) { return NextResponse.json({ error: "Invalid API key" }, { status: 401 }); } const body = await req.json(); const parsed = taskSchema.safeParse(body); if (!parsed.success) { return NextResponse.json( { error: "Validation failed", details: parsed.error.flatten() }, { status: 400 } ); } const { summary, durationMs, model, toolsUsed } = parsed.data; const now = new Date(); const insertResult = await db.insert(tasks).values({ clawId: claw.id, summary, durationMs, model: model ?? null, toolsUsed: toolsUsed ?? null, timestamp: now, }); await db .update(claws) .set({ totalTasks: sql`${claws.totalTasks} + 1`, updatedAt: now }) .where(eq(claws.id, claw.id)); await incrementGlobalStat("total_tasks"); await incrementGlobalStat("tasks_today"); await incrementHourlyActivity(); await publishEvent({ type: "task", clawId: claw.id, clawName: claw.name, city: claw.city, country: claw.country, summary, durationMs, }); return NextResponse.json({ ok: true, taskId: insertResult[0].insertId, }); } catch (error) { console.error("Task error:", error); return NextResponse.json( { error: "Internal server error" }, { status: 500 } ); } }