import { entityRegistry, ensureInitialized } from "../../entities/registry.js";
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) {
  if (!entityConfig.enabled) {
    return false;
  }
  switch (operation) {
    case "list":
    case "read":
    case "create":
    case "update":
    case "delete":
      return entityConfig.enabled;
    default:
      return false;
  }
}
export {
  getGenericEntities,
  resolveEntityFromUrl,
  validateEntityOperation
};
