import { readFile } from "node:fs/promises";
import { resolve, sep } from "node:path";
import type { ScanSource } from "./types.js";
import { normalizeScanSourcePath } from "./paths.js";

function isInsideRoot(rootDir: string, candidate: string): boolean {
  return candidate === rootDir || candidate.startsWith(`${rootDir}${sep}`);
}

export function createLocalScanSource(rootDir: string): ScanSource {
  const root = resolve(rootDir);

  return {
    kind: "local",
    root,
    async readFile(path: string): Promise<string | null> {
      const relPath = normalizeScanSourcePath(path);
      if (!relPath) return null;

      const absolutePath = resolve(root, relPath);
      if (!isInsideRoot(root, absolutePath)) return null;

      try {
        return await readFile(absolutePath, "utf-8");
      } catch {
        return null;
      }
    },
  };
}
