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

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const limit = parseInt(searchParams.get("limit") || "20");
    const offset = parseInt(searchParams.get("offset") || "0");

    const allTasks = await db
      .select()
      .from(tasks)
      .orderBy(desc(tasks.updatedAt))
      .limit(limit)
      .offset(offset);

    const countResult = await db
      .select({ count: count() })
      .from(tasks);
    const total = countResult[0].count;

    return NextResponse.json({
      tasks: allTasks,
      total,
      limit,
      offset,
    });
  } catch (error) {
    console.error("Error fetching tasks:", error);
    return NextResponse.json(
      { error: "Failed to fetch tasks" },
      { status: 500 }
    );
  }
}
