import { NextResponse } from "next/server";
import { getContents } from "@/lib/github";

export async function GET(request) {
  const { searchParams } = new URL(request.url);
  const path = searchParams.get("path") || "";
  try {
    const data = await getContents(path);
    // Always return an array (directory listing)
    const items = Array.isArray(data) ? data : [data];
    const result = items.map(
      ({ name, path, type, sha, size, download_url }) => ({
        name,
        path,
        type,
        sha,
        size,
        download_url,
      }),
    );
    return NextResponse.json(result);
  } catch (err) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}