import { runMdschema } from "../../mdschema";
import { type CommandResult, success, silentFailure } from "./command-result";

export interface CheckTarget {
  glob: string;
  schemaPath: string;
}

export async function runCheck(targets: CheckTarget[], cwd: string): Promise<CommandResult> {
  const results = await Promise.all(
    targets.map(async (target) => {
      const { exitCode, stdout, stderr } = await runMdschema(
        ["check", target.glob, "--schema", target.schemaPath],
        cwd,
      );

      if (stdout.trim()) console.log(stdout);
      if (stderr.trim()) console.error(stderr);

      return exitCode;
    }),
  );

  if (results.includes(2)) return silentFailure(2);
  return results.some((code) => code !== 0) ? silentFailure() : success();
}
