import { entityRegistry, ensureInitialized } from "../../entities/registry";
import { existsSync } from "fs";
import { join } from "path";
async function resolveEntityFromUrl(pathname) {
  const segments = pathname.split("/").filter(Boolean);
  if (segments.length < 3 || segments[0] !== "api" || segments[1] !== "v1") {
    return {
      entityName: "",
      entityConfig: null,
      hasCustomOverride: false,
      isValidEntity: false
    };
  }
  const entitySlug = segments[2];
  if (isCorePath(entitySlug)) {
    return {
      entityName: entitySlug,
      entityConfig: null,
      hasCustomOverride: true,
      // Treat core as override
      isValidEntity: false
    };
  }
  await ensureInitialized();
  const entityConfig = entityRegistry.getBySlug(entitySlug);
  if (!entityConfig) {
    return {
      entityName: entitySlug,
      entityConfig: null,
      hasCustomOverride: false,
      isValidEntity: false
    };
  }
  const hasCustomOverride = await checkCustomOverride(entitySlug);
  return {
    entityName: entityConfig.slug,
    // Use slug as entityName for new structure
    entityConfig,
    hasCustomOverride,
    isValidEntity: true
  };
}
async function checkCustomOverride(entityName) {
  try {
    const customRoutePath = join(
      process.cwd(),
      "app",
      "api",
      "v1",
      "(contents)",
      entityName,
      "route.ts"
    );
    return existsSync(customRoutePath);
  } catch (error) {
    console.warn(`Error checking custom override for ${entityName}:`, error);
    return false;
  }
}
function isCorePath(entityName) {
  const corePaths = [
    "users",
    "api-keys",
    "auth",
    "system",
    "health",
    "internal",
    "admin",
    "debug"
  ];
  return corePaths.includes(entityName);
}
async function getGenericEntities() {
  await ensureInitialized();
  const allEntities = entityRegistry.getAll();
  return allEntities.filter((entity) => entity.enabled).map((entity) => entity.slug).filter((slug) => !isCorePath(slug));
}
function validateEntityOperation(entityConfig, operation) {
  var _a, _b, _c, _d, _e, _f;
  if (!entityConfig.enabled) {
    return false;
  }
  switch (operation) {
    case "list":
    case "read":
      return entityConfig.enabled;
    case "create":
      return entityConfig.enabled && (((_b = (_a = entityConfig.permissions) == null ? void 0 : _a.actions) == null ? void 0 : _b.some((a) => a.action === "create")) ?? true);
    case "update":
      return entityConfig.enabled && (((_d = (_c = entityConfig.permissions) == null ? void 0 : _c.actions) == null ? void 0 : _d.some((a) => a.action === "update")) ?? true);
    case "delete":
      return entityConfig.enabled && (((_f = (_e = entityConfig.permissions) == null ? void 0 : _e.actions) == null ? void 0 : _f.some((a) => a.action === "delete")) ?? true);
    default:
      return false;
  }
}
export {
  getGenericEntities,
  resolveEntityFromUrl,
  validateEntityOperation
};
