/**
 * GET /api/fs/browse?path=/some/dir
 * Returns immediate subdirectories of `path` (defaults to $HOME).
 * Used by the Add Project folder picker so users don't have to type
 * paths. Auth-gated by middleware like the rest of /api/*.
 */

import { NextResponse } from 'next/server';
import { readdirSync, statSync } from 'node:fs';
import { join, resolve, dirname } from 'node:path';
import { homedir } from 'node:os';

export async function GET(req: Request) {
  const url = new URL(req.url);
  const requested = url.searchParams.get('path') || homedir();
  const path = resolve(requested);

  try {
    const stat = statSync(path);
    if (!stat.isDirectory()) {
      return NextResponse.json({ ok: false, error: 'not a directory', path }, { status: 400 });
    }
    const entries = readdirSync(path, { withFileTypes: true })
      .filter(e => (e.isDirectory() || e.isSymbolicLink()) && !e.name.startsWith('.'))
      .map(e => ({ name: e.name, path: join(path, e.name) }))
      .sort((a, b) => a.name.localeCompare(b.name));
    return NextResponse.json({
      ok: true,
      path,
      parent: path === '/' ? null : dirname(path),
      home: homedir(),
      entries,
    });
  } catch (err) {
    return NextResponse.json({ ok: false, error: (err as Error).message, path }, { status: 404 });
  }
}
