import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { readdirSync, statSync, existsSync } from "fs";
import { join, resolve, sep, dirname } from "path";

export async function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams;
  const dirPath = searchParams.get("path") || "";

  try {
    const resolved = dirPath ? resolve(dirPath) : resolve("/");
    if (!existsSync(resolved)) {
      return NextResponse.json({ error: "Dossier introuvable" }, { status: 404 });
    }

    const stat = statSync(resolved);
    if (!stat.isDirectory()) {
      return NextResponse.json({ error: "Ce n'est pas un dossier" }, { status: 400 });
    }

    const entries = readdirSync(resolved, { withFileTypes: true });
    const folders = entries
      .filter((e) => e.isDirectory() && !e.name.startsWith("."))
      .map((e) => {
        const full = join(resolved, e.name);
        const isGitRepo = existsSync(join(full, ".git"));
        return { name: e.name, path: full, isGitRepo };
      })
      .sort((a, b) => a.name.localeCompare(b.name));

    const parent = dirname(resolved);
    const isRoot = resolved === sep || resolved.match(/^[A-Z]:\\$/i);
    const parentPath = isRoot ? null : parent;

    return NextResponse.json({
      path: resolved,
      parentPath,
      isRoot,
      folders,
    });
  } catch (err: any) {
    if (err.code === "EACCES" || err.code === "EPERM") {
      return NextResponse.json({ error: "Permission refusée" }, { status: 403 });
    }
    return NextResponse.json({ error: err?.message || "Erreur" }, { status: 500 });
  }
}
