import { TestTube } from "lucide-react";
import { entityRegistry } from "./registry.js";
import { entityPerformanceMonitor } from "./performance.js";
function createMockEntityConfig(overrides = {}) {
  const defaultConfig = {
    slug: "test-entities",
    enabled: true,
    names: {
      singular: "Test Entity",
      plural: "Test Entities"
    },
    icon: TestTube,
    access: {
      public: false,
      api: true,
      metadata: true,
      shared: false
      // Test entities are private to creator
    },
    ui: {
      dashboard: {
        showInMenu: true,
        showInTopbar: true
      },
      public: {
        hasArchivePage: false,
        hasSinglePage: false
      },
      features: {
        searchable: true,
        sortable: true,
        filterable: true,
        bulkOperations: true,
        importExport: false
      }
    },
    // Permissions are now defined centrally in permissions.config.ts
    i18n: {
      fallbackLocale: "en",
      loaders: {
        en: async () => ({}),
        es: async () => ({})
      }
    },
    fields: [
      {
        name: "title",
        type: "text",
        required: true,
        display: {
          label: "Title",
          description: "Entity title",
          placeholder: "Enter title...",
          showInList: true,
          showInDetail: true,
          showInForm: true,
          order: 1
        },
        api: {
          searchable: true,
          sortable: true,
          readOnly: false
        }
      },
      {
        name: "description",
        type: "text",
        required: false,
        display: {
          label: "Description",
          description: "Entity description",
          placeholder: "Enter description...",
          showInList: false,
          showInDetail: true,
          showInForm: true,
          order: 2
        },
        api: {
          searchable: true,
          sortable: false,
          readOnly: false
        }
      }
    ]
  };
  return { ...defaultConfig, ...overrides };
}
function createMockEntityData(entityConfig, count = 1) {
  const mockData = [];
  for (let i = 0; i < count; i++) {
    const data = {
      id: `test-${entityConfig.slug}-${i + 1}`,
      createdAt: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1e3).toISOString(),
      updatedAt: (/* @__PURE__ */ new Date()).toISOString()
    };
    entityConfig.fields.forEach((field) => {
      data[field.name] = generateMockFieldValue(field);
    });
    mockData.push(data);
  }
  return mockData;
}
function generateMockFieldValue(field) {
  switch (field.type) {
    case "text":
      return `Test ${field.display.label} ${Math.floor(Math.random() * 1e3)}`;
    case "textarea":
      return `This is a longer test description for ${field.display.label}. It contains multiple sentences to simulate real content.`;
    case "number":
      return Math.floor(Math.random() * 1e3);
    case "boolean":
      return Math.random() > 0.5;
    case "date":
      return new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1e3).toISOString().split("T")[0];
    case "datetime":
      return new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1e3).toISOString();
    case "email":
      return `test.${field.name}${Math.floor(Math.random() * 1e3)}@example.com`;
    case "url":
      return `https://example.com/${field.name}/${Math.floor(Math.random() * 1e3)}`;
    case "select":
      if (field.options && field.options.length > 0) {
        const randomOption = field.options[Math.floor(Math.random() * field.options.length)];
        return randomOption.value;
      }
      return "option1";
    case "multiselect":
      if (field.options && field.options.length > 0) {
        const selectedOptions = field.options.filter(() => Math.random() > 0.5).map((option) => option.value);
        return selectedOptions.length > 0 ? selectedOptions : [field.options[0].value];
      }
      return ["option1"];
    case "json":
      return {
        test: true,
        value: Math.floor(Math.random() * 100),
        nested: { property: "test value" }
      };
    default:
      return `Mock ${field.type} value`;
  }
}
function createMockUser(role = "member", plan = "free", flags = []) {
  return {
    id: `test-user-${Math.floor(Math.random() * 1e3)}`,
    role,
    plan,
    flags,
    email: `test.user${Math.floor(Math.random() * 1e3)}@example.com`
  };
}
function validateEntityConfig(config) {
  var _a, _b, _c, _d, _e, _f, _g, _h;
  const errors = [];
  if (!((_a = config.slug) == null ? void 0 : _a.trim())) errors.push("Entity slug is required");
  if (!((_c = (_b = config.names) == null ? void 0 : _b.singular) == null ? void 0 : _c.trim())) errors.push("Entity singular name is required");
  if (!((_e = (_d = config.names) == null ? void 0 : _d.plural) == null ? void 0 : _e.trim())) errors.push("Entity plural name is required");
  if (!config.icon) errors.push("Icon is required");
  if (typeof config.enabled !== "boolean") {
    errors.push("enabled must be a boolean");
  }
  if (typeof ((_f = config.access) == null ? void 0 : _f.api) !== "boolean") {
    errors.push("access.api must be a boolean");
  }
  if (typeof ((_g = config.access) == null ? void 0 : _g.public) !== "boolean") {
    errors.push("access.public must be a boolean");
  }
  if (typeof ((_h = config.access) == null ? void 0 : _h.metadata) !== "boolean") {
    errors.push("access.metadata must be a boolean");
  }
  if (!Array.isArray(config.fields)) {
    errors.push("fields must be an array");
  } else {
    config.fields.forEach((field, index) => {
      var _a2;
      if (!((_a2 = field.name) == null ? void 0 : _a2.trim())) errors.push(`Field at index ${index} must have a name`);
      if (!field.type) errors.push(`Field "${field.name}" must have a type`);
      if (typeof field.required !== "boolean") {
        errors.push(`Field "${field.name}" required property must be a boolean`);
      }
    });
  }
  return { valid: errors.length === 0, errors };
}
function testEntityAccess(entityConfig) {
  const results = [];
  const adminCanRead = true;
  results.push({
    test: "Admin Read Permission",
    passed: adminCanRead,
    message: adminCanRead ? "Admin can read" : "Admin cannot read (unexpected)"
  });
  const memberFreeCanRead = true;
  const memberPremiumCanRead = true;
  results.push({
    test: "Member Free Plan Read",
    passed: memberFreeCanRead,
    // All users can read now
    message: `Member with free plan read access: ${memberFreeCanRead}`
  });
  results.push({
    test: "Member Premium Plan Read",
    passed: memberPremiumCanRead,
    // All users can read now
    message: `Member with premium plan read access: ${memberPremiumCanRead}`
  });
  const passed = results.every((result) => result.passed);
  return { passed, results };
}
async function performanceTestEntity(entityConfig, operations = ["create", "read", "update", "delete"]) {
  const results = [];
  for (const operation of operations) {
    const times = [];
    const iterations = 100;
    for (let i = 0; i < iterations; i++) {
      const startTime = performance.now();
      switch (operation) {
        case "create":
          createMockEntityData(entityConfig, 1);
          break;
        case "read":
          entityRegistry.get(entityConfig.slug);
          break;
        case "update":
          createMockEntityData(entityConfig, 1);
          break;
        case "delete":
          validateEntityConfig(entityConfig);
          break;
      }
      const endTime = performance.now();
      times.push(endTime - startTime);
    }
    results.push({
      operation,
      averageTime: times.reduce((sum, time) => sum + time, 0) / times.length,
      minTime: Math.min(...times),
      maxTime: Math.max(...times),
      iterations
    });
  }
  return results;
}
async function integrationTestEntity(entityConfig) {
  const steps = [];
  let startTime = performance.now();
  try {
    const validation = validateEntityConfig(entityConfig);
    steps.push({
      step: "Configuration Validation",
      passed: validation.valid,
      duration: performance.now() - startTime,
      error: validation.valid ? void 0 : validation.errors.join(", ")
    });
  } catch (error) {
    steps.push({
      step: "Configuration Validation",
      passed: false,
      duration: performance.now() - startTime,
      error: error instanceof Error ? error.message : "Unknown error"
    });
  }
  startTime = performance.now();
  try {
    entityRegistry.register(entityConfig);
    steps.push({
      step: "Entity Registration",
      passed: true,
      duration: performance.now() - startTime
    });
  } catch (error) {
    steps.push({
      step: "Entity Registration",
      passed: false,
      duration: performance.now() - startTime,
      error: error instanceof Error ? error.message : "Unknown error"
    });
  }
  startTime = performance.now();
  try {
    const accessTest = testEntityAccess(entityConfig);
    steps.push({
      step: "Permission Testing",
      passed: accessTest.passed,
      duration: performance.now() - startTime,
      error: accessTest.passed ? void 0 : "Some access tests failed"
    });
  } catch (error) {
    steps.push({
      step: "Permission Testing",
      passed: false,
      duration: performance.now() - startTime,
      error: error instanceof Error ? error.message : "Unknown error"
    });
  }
  startTime = performance.now();
  try {
    const mockData = createMockEntityData(entityConfig, 5);
    steps.push({
      step: "Mock Data Generation",
      passed: mockData.length === 5,
      duration: performance.now() - startTime,
      error: mockData.length !== 5 ? "Failed to generate expected number of records" : void 0
    });
  } catch (error) {
    steps.push({
      step: "Mock Data Generation",
      passed: false,
      duration: performance.now() - startTime,
      error: error instanceof Error ? error.message : "Unknown error"
    });
  }
  const passed = steps.every((step) => step.passed);
  return { passed, steps };
}
function cleanupTestEntities() {
  const testEntities = entityRegistry.getAll().filter(
    (entity) => entity.slug.startsWith("test-") || entity.slug.includes("mock")
  );
  testEntities.forEach((entity) => {
    try {
      console.log(`Would remove test entity: ${entity.slug}`);
    } catch (error) {
      console.warn(`Failed to remove test entity ${entity.slug}:`, error);
    }
  });
  entityPerformanceMonitor.clear();
}
function generateTestReport(entityConfig, validationResults, accessResults, integrationResults) {
  let report = `# Entity Test Report: ${entityConfig.names.singular}

`;
  report += "## Configuration Validation\n\n";
  if (validationResults.valid) {
    report += "\u2705 **PASSED** - Configuration is valid\n\n";
  } else {
    report += "\u274C **FAILED** - Configuration has errors:\n\n";
    validationResults.errors.forEach((error) => {
      report += `- ${error}
`;
    });
    report += "\n";
  }
  report += "## Access Testing\n\n";
  if (accessResults.passed) {
    report += "\u2705 **PASSED** - All access tests passed\n\n";
  } else {
    report += "\u274C **FAILED** - Some access tests failed:\n\n";
    accessResults.results.forEach((result) => {
      const status = result.passed ? "\u2705" : "\u274C";
      report += `${status} ${result.test}: ${result.message}
`;
    });
    report += "\n";
  }
  report += "## Integration Testing\n\n";
  if (integrationResults.passed) {
    report += "\u2705 **PASSED** - All integration tests passed\n\n";
  } else {
    report += "\u274C **FAILED** - Some integration tests failed:\n\n";
  }
  integrationResults.steps.forEach((step) => {
    const status = step.passed ? "\u2705" : "\u274C";
    const duration = step.duration.toFixed(2);
    report += `${status} ${step.step}: ${duration}ms`;
    if (step.error) {
      report += ` - Error: ${step.error}`;
    }
    report += "\n";
  });
  report += "\n";
  const overallPassed = validationResults.valid && accessResults.passed && integrationResults.passed;
  report += "## Overall Result\n\n";
  if (overallPassed) {
    report += "\u{1F389} **ENTITY TEST PASSED** - Ready for production use!\n";
  } else {
    report += "\u26A0\uFE0F **ENTITY TEST FAILED** - Requires fixes before production use.\n";
  }
  return report;
}
export {
  cleanupTestEntities,
  createMockEntityConfig,
  createMockEntityData,
  createMockUser,
  generateMockFieldValue,
  generateTestReport,
  integrationTestEntity,
  performanceTestEntity,
  testEntityAccess,
  validateEntityConfig
};
