import { d as defineEventHandler, dL as optionalAuth, j as getQuery, c as createError, eV as validateSearchQuery, bE as MAX_SEARCH_QUERY_LENGTH, ev as clampLimit, ew as clampOffset, a as getSchemaManager, eW as validateCrossSearchContentTypes, bT as requirePermission } from '../../nitro/nitro.mjs';
import { getSearchService } from '../../_/index.mjs';
import 'node:crypto';
import 'jsonwebtoken';
import 'node:fs';
import 'node:module';
import 'node:path';
import 'node:url';
import 'node:http';
import 'node:https';
import 'node:events';
import 'node:buffer';
import 'pino';
import 'drizzle-orm/better-sqlite3';
import 'drizzle-orm/node-postgres';
import 'drizzle-orm/mysql2';
import 'better-sqlite3';
import 'pg';
import 'mysql2/promise';
import 'drizzle-orm';
import 'fs';
import 'path';
import 'prom-client';
import 'bcryptjs';
import '@node-rs/argon2';
import 'node:async_hooks';
import 'crypto';
import 'node:dns';
import 'node:util';
import 'node:net';
import 'fs/promises';
import 'url';
import 'semver';

const index_get = defineEventHandler(async (event) => {
  try {
    await optionalAuth(event);
    const query = getQuery(event);
    const searchQuery = typeof query.query === "string" ? query.query.trim() : "";
    if (!searchQuery) {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: 'Query parameter "query" is required'
      });
    }
    const queryViolations = validateSearchQuery(searchQuery);
    if (queryViolations.length > 0) {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: `Search query too long (max ${MAX_SEARCH_QUERY_LENGTH} characters)`
      });
    }
    const limit = clampLimit(query.limit ? parseInt(String(query.limit)) : 25);
    const offset = clampOffset(query.offset ? parseInt(String(query.offset)) : 0);
    const includeMedia = query.includeMedia === "true";
    const highlight = query.highlight === "true";
    const schemaManager = getSchemaManager();
    let contentTypeNames;
    if (typeof query.contentTypes === "string" && query.contentTypes.trim()) {
      contentTypeNames = query.contentTypes.split(",").map((ct) => ct.trim()).filter(Boolean);
    } else {
      contentTypeNames = schemaManager.getAllSchemas().filter((s) => s.kind === "collectionType").map((s) => s.info.singularName);
    }
    const typeViolations = validateCrossSearchContentTypes(contentTypeNames);
    if (typeViolations.length > 0) {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: typeViolations[0].message
      });
    }
    const validContentTypes = [];
    for (const ct of contentTypeNames) {
      const schema = schemaManager.getSchema(ct);
      if (schema) {
        validContentTypes.push(ct);
      }
    }
    const permittedContentTypes = [];
    for (const ct of validContentTypes) {
      try {
        await requirePermission(
          event.context.user,
          ct,
          "read",
          event.context.adminUser,
          event.context.apiToken
        );
        permittedContentTypes.push(ct);
      } catch {
      }
    }
    const searchService = getSearchService();
    const startTime = Date.now();
    const allHits = [];
    let totalCount = 0;
    const windowSize = limit + offset;
    const searchPromises = permittedContentTypes.map(async (ct) => {
      const result = await searchService.search(ct, {
        query: searchQuery,
        limit: windowSize,
        offset: 0,
        highlight: highlight ? { enabled: true } : void 0
      });
      return result;
    });
    if (includeMedia) {
      try {
        await requirePermission(
          event.context.user,
          "media",
          "read",
          event.context.adminUser,
          event.context.apiToken
        );
        searchPromises.push(
          searchService.search("media", {
            query: searchQuery,
            limit: windowSize,
            offset: 0,
            highlight: highlight ? { enabled: true } : void 0
          })
        );
      } catch {
      }
    }
    const results = await Promise.all(searchPromises);
    for (const result of results) {
      allHits.push(...result.hits);
      totalCount += result.total;
    }
    allHits.sort((a, b) => {
      if (a.score !== void 0 && b.score !== void 0) {
        return b.score - a.score;
      }
      return 0;
    });
    const paginatedHits = allHits.slice(offset, offset + limit);
    const processingTimeMs = Date.now() - startTime;
    return {
      success: true,
      data: paginatedHits,
      total: totalCount,
      limit,
      offset,
      processingTimeMs,
      contentTypes: permittedContentTypes,
      includeMedia
    };
  } catch (error) {
    const err = error;
    if (err.statusCode) {
      throw error;
    }
    console.error("Cross-content search error:", error);
    throw createError({
      statusCode: 500,
      statusMessage: "Internal Server Error",
      message: "Search failed"
    });
  }
});

export { index_get as default };
//# sourceMappingURL=index.get6.mjs.map
