import { auth } from "@/lib/auth";
import { db } from "@/lib/db";
import { historialCambios } from "@/lib/schema";
import { desc, eq } from "drizzle-orm";

export async function GET(req: Request) {
  const session = await auth();
  if (!session) return Response.json({ error: "Unauthorized" }, { status: 401 });

  const url = new URL(req.url);
  const tabla = url.searchParams.get('tabla');

  const rows = tabla
    ? await db.select().from(historialCambios)
        .where(eq(historialCambios.tabla, tabla))
        .orderBy(desc(historialCambios.createdAt)).limit(100)
    : await db.select().from(historialCambios)
        .orderBy(desc(historialCambios.createdAt)).limit(100);

  return Response.json(rows);
}
