import path from "node:path";
import fg from "fast-glob";
import { APP_PATHS } from "../../lib/paths";
import type { CheckError, SyncCheckResult } from "../../lib/sync-check/shared";

/**
 * Spec-fixture sync check: validates that each e2e spec file
 * has a corresponding fixture file with the same basename under e2e/fixtures/.
 * e2e/tests/<name>.spec.ts → e2e/fixtures/<name>.ts
 */
export async function runSpecFixtureSyncCheck(
  appRoot: string,
  cwd: string,
): Promise<SyncCheckResult> {
  const errors: CheckError[] = [];

  const specPattern = `${appRoot}/${APP_PATHS.tests.e2e}/tests/**/*.spec.ts`;
  const specFiles = await fg(specPattern, { cwd });

  const fixturePattern = `${appRoot}/${APP_PATHS.tests.e2e}/fixtures/*.ts`;
  const fixtureFiles = await fg(fixturePattern, { cwd });
  const fixtureBasenames = new Set(fixtureFiles.map((p) => path.basename(p, ".ts")));

  for (const specFile of specFiles) {
    const specBasename = path.basename(specFile, ".spec.ts");

    if (!fixtureBasenames.has(specBasename)) {
      errors.push({
        type: "missing-spec-fixture",
        category: "e2e-fixture",
        sourcePath: specFile,
        expectedBasename: `${specBasename}.ts`,
      });
    }
  }

  return { errors, filesChecked: specFiles.length + fixtureFiles.length };
}
