import { NextRequest, NextResponse } from "next/server";
import fs from "fs";
import path from "path";
import { getAllowedRoots, isPathAllowed, searchFilesInCwd } from "@/lib/file-access";

export const dynamic = "force-dynamic";

// GET /api/files/search?cwd=<abs>&q=<query>&limit=30
export async function GET(request: NextRequest) {
  try {
    const cwd = request.nextUrl.searchParams.get("cwd");
    const q = request.nextUrl.searchParams.get("q") ?? "";
    const limitRaw = request.nextUrl.searchParams.get("limit");
    const limit = Math.min(Math.max(Number(limitRaw) || 30, 1), 100);

    if (!cwd) {
      return NextResponse.json({ error: "cwd is required" }, { status: 400 });
    }

    const resolved = path.resolve(cwd);
    let stat: fs.Stats;
    try {
      stat = fs.statSync(resolved);
    } catch {
      return NextResponse.json({ error: "Directory not found" }, { status: 404 });
    }
    if (!stat.isDirectory()) {
      return NextResponse.json({ error: "cwd is not a directory" }, { status: 400 });
    }

    const allowedRoots = await getAllowedRoots();
    // Also allow the explicit cwd itself once validated as a directory (new sessions
    // may not yet appear in the sessions-derived root set).
    allowedRoots.add(resolved);
    if (!isPathAllowed(resolved, allowedRoots)) {
      return NextResponse.json({ error: "Access denied" }, { status: 403 });
    }

    const items = searchFilesInCwd(resolved, q.trim(), { limit });
    return NextResponse.json({ items });
  } catch (e) {
    return NextResponse.json(
      { error: e instanceof Error ? e.message : String(e) },
      { status: 500 }
    );
  }
}
