import { db } from "@/app/db/db";
import { tasks } from "@/app/db/schema/tasks/tasks";
import { subTasks } from "@/app/db/schema/tasks/subtask";
import { eq, count, sql } from "drizzle-orm";
import { NextRequest, NextResponse } from "next/server";

export async function GET(
  _request: NextRequest,
  { params }: { params: Promise<{ taskId: string }> }
) {
  const { taskId } = await params;

  try {
    const [row] = await db
      .select({
        id: tasks.id,
        taskSource: tasks.taskSource,
        status: tasks.status,
        service: tasks.service,
        jobStarted: tasks.jobStarted,
        jobCompleted: tasks.jobCompleted,
        updatedAt: tasks.updatedAt,
        totalSubtasks: count(subTasks.id),
        completedSubtasks: sql<number>`count(case when lower(${subTasks.status}) in ('completed', 'complete') then 1 end)::int`,
        failedSubtasks: sql<number>`count(case when lower(${subTasks.status}) in ('failed', 'failure', 'error') then 1 end)::int`,
      })
      .from(tasks)
      .leftJoin(subTasks, eq(subTasks.taskId, tasks.id))
      .where(eq(tasks.id, taskId))
      .groupBy(tasks.id)
      .limit(1);

    if (!row) return NextResponse.json({ error: "Not found" }, { status: 404 });

    return NextResponse.json(row);
  } catch (error) {
    console.error("Error fetching task summary:", error);
    return NextResponse.json({ error: "Failed to fetch task summary" }, { status: 500 });
  }
}
