import { NextRequest, NextResponse } from "next/server";
import { readdirSync, statSync } from "node:fs";
import { join, resolve, relative } from "node:path";
import type { FileEntry } from "@/lib/file-types";
import { getDb } from "@/lib/db";

function sanitizePath(sourceRoot: string, reqPath: string): string | null {
  if (reqPath.includes("..") || reqPath.startsWith("/")) return null;
  const full = resolve(sourceRoot, reqPath);
  if (!full.startsWith(sourceRoot)) return null;
  return full;
}

export async function POST(request: NextRequest) {
  try {
    const { repository_id, path: reqPath = "." } = await request.json();
    if (!repository_id || typeof repository_id !== "string") {
      return NextResponse.json({ error: "repository_id is required" }, { status: 400 });
    }

    const db = await getDb();
    const { rows } = await db.query(
      "SELECT source_path FROM repositories WHERE id = $1",
      [repository_id],
    );
    if (rows.length === 0) {
      return NextResponse.json({ error: "Repository not found" }, { status: 404 });
    }

    const reposBase = process.env.REPOS_PATH ? resolve(process.env.REPOS_PATH, "..") : process.cwd();
    const sourceRoot = resolve(reposBase, rows[0].source_path);
    const fullPath = sanitizePath(sourceRoot, reqPath);

    if (!fullPath) {
      return NextResponse.json({ error: "Invalid path" }, { status: 400 });
    }

    const stat = statSync(fullPath, { throwIfNoEntry: false });
    if (!stat || !stat.isDirectory()) {
      return NextResponse.json({ error: "Not a directory" }, { status: 400 });
    }

    const dirents = readdirSync(fullPath, { withFileTypes: true });
    const entries: FileEntry[] = dirents
      .filter((d) => !d.name.startsWith("."))
      .map((d) => ({
        name: d.name,
        path: relative(sourceRoot, join(fullPath, d.name)),
        type: d.isDirectory() ? ("directory" as const) : ("file" as const),
      }))
      .sort((a, b) => {
        if (a.type !== b.type) return a.type === "directory" ? -1 : 1;
        return a.name.localeCompare(b.name);
      });

    return NextResponse.json({ path: reqPath, entries });
  } catch (err) {
    const msg = err instanceof Error ? err.message : "Unknown error";
    return NextResponse.json({ error: msg }, { status: 500 });
  }
}
