import { NextResponse } from "next/server";
import {
  execInDevContainer,
  ensureDevContainer,
} from "../../../../../lib/dev-container";
import { authSession } from "../../../../../lib/auth/session-server";
import { queryOne } from "../../../../../lib/db-postgres";
import type { VibnWorkspace } from "../../../../../lib/workspaces";

export const dynamic = "force-dynamic";

export async function GET(
  req: Request,
  ctx: { params: Promise<{ projectId: string }> },
) {
  try {
    const { projectId } = await ctx.params;
    const { searchParams } = new URL(req.url);
    const workspace = searchParams.get("workspace") || "";

    const session = await authSession();
    if (!session?.user?.email || !workspace) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    // Fetch project details to get the slug
    const r = await queryOne<{ data: { slug: string } }>(
      `SELECT data FROM fs_projects WHERE id = $1`,
      [projectId],
    );
    if (!r?.data?.slug) {
      return NextResponse.json({ error: "Project not found" }, { status: 404 });
    }
    const projectSlug = r.data.slug;

    // Ensure the container is active
    await ensureDevContainer({
      projectId,
      projectSlug,
      projectName: projectSlug,
      workspace: { slug: workspace } as unknown as VibnWorkspace,
    });

    // Run a fast find inside the dev container, excluding build/node_modules/git artifacts
    const result = (await execInDevContainer({
      projectId,
      command: `find . -maxdepth 4 -not -path "*/node_modules/*" -not -path "*/.git/*" -not -path "*/.next/*" -not -path "*/dist/*" -not -path "*/build/*" | sort | sed 's|^\\./||'`,
    })) as unknown as { exitCode: number; stdout: string };

    if (result.exitCode !== 0) {
      return NextResponse.json({ files: [] });
    }

    const files = result.stdout
      .split("\n")
      .map((f: string) => f.trim())
      .filter((f: string) => f && f !== "." && f !== "..");

    return NextResponse.json({ files });
  } catch (err) {
    return NextResponse.json({ error: String(err) }, { status: 500 });
  }
}
