import { dK as defineContentEventHandler, c as createError, dL as optionalAuth, bT as requirePermission, G as createContentManager, er as validateAggregateExpressions, es as validateGroupByFields, et as validateFilterOperators, eu as validateHavingClauses, dR as calculateQueryCost } from '../../../../nitro/nitro.mjs';
import { a as parseQueryFilters, s as setQueryCostResponseHeaders, m as mapContentApiError } from '../../../../_/api-helpers.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';
import '../../../../_/delivery-metrics.mjs';

const aggregate_get = defineContentEventHandler("list", async (event, input) => {
  var _a, _b;
  try {
    const contentType = (_a = event.context.params) == null ? void 0 : _a.contentType;
    if (!contentType) {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: "Content type is required"
      });
    }
    await optionalAuth(event);
    await requirePermission(
      event.context.user,
      contentType,
      "read",
      event.context.adminUser,
      event.context.apiToken
    );
    const query = input || {};
    const aggregate = {};
    if (query.function && typeof query.function === "string") {
      const func = query.function.toLowerCase();
      const field = query.field && typeof query.field === "string" ? query.field : "*";
      if (func === "count") {
        aggregate.count = field === "*" || field === "id" ? "*" : `count:${field}`;
      } else if (["sum", "avg", "min", "max"].includes(func)) {
        if (field === "*") {
          throw createError({
            statusCode: 400,
            statusMessage: "Bad Request",
            message: `${func} function requires a field parameter`
          });
        }
        aggregate[func] = `${func}:${field}`;
      }
    }
    for (const [key, value] of Object.entries(query)) {
      const match = key.match(/^aggregate\[(.+)\]$/);
      if (match && typeof value === "string") {
        aggregate[match[1]] = value;
      }
    }
    if (Object.keys(aggregate).length === 0) {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: "At least one aggregate function is required"
      });
    }
    const groupBy = [];
    if (query.groupBy && typeof query.groupBy === "string") {
      groupBy.push(query.groupBy);
    } else if (Array.isArray(query.groupBy)) {
      groupBy.push(...query.groupBy.filter((v) => typeof v === "string"));
    }
    for (const [key, value] of Object.entries(query)) {
      if (key === "groupBy[]" && typeof value === "string") {
        groupBy.push(value);
      }
    }
    const filters = parseQueryFilters(query);
    const having = {};
    for (const [key, value] of Object.entries(query)) {
      const match = key.match(/^having\[(.+?)\](?:\[(.+?)\])?$/);
      if (match) {
        const alias = match[1];
        const operator = match[2];
        if (operator) {
          if (!having[alias]) {
            having[alias] = {};
          }
          having[alias][operator] = value;
        } else {
          having[alias] = value;
        }
      }
    }
    const contentManager = createContentManager(contentType);
    const schema = contentManager.getSchema();
    const guardrailWarnings = [];
    const aggregateViolations = validateAggregateExpressions(aggregate, schema);
    guardrailWarnings.push(...aggregateViolations);
    const groupByValidation = validateGroupByFields(groupBy, schema);
    guardrailWarnings.push(...groupByValidation.violations);
    const filterViolations = validateFilterOperators(filters);
    guardrailWarnings.push(...filterViolations);
    const havingViolations = validateHavingClauses(having, Object.keys(aggregate));
    guardrailWarnings.push(...havingViolations);
    if (aggregateViolations.length > 0 || filterViolations.length > 0 || havingViolations.length > 0) {
      const errors = [...aggregateViolations, ...filterViolations, ...havingViolations].map((violation) => violation.message).join("; ");
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: `Invalid aggregate query: ${errors}`
      });
    }
    const result = await contentManager.aggregate({
      aggregate,
      groupBy: groupByValidation.valid,
      filters,
      having
    });
    const cost = calculateQueryCost({
      limit: 0,
      hasFilters: Object.keys(filters).length > 0,
      filterConditions: Object.keys(filters).length,
      relationJoins: 0,
      populateFields: 0,
      searchFields: 0,
      hasAggregate: true,
      groupByFields: groupByValidation.valid.length
    });
    setQueryCostResponseHeaders(event, cost, guardrailWarnings);
    return {
      success: true,
      ...result
    };
  } catch (error) {
    mapContentApiError(error, {
      routeLabel: `GET /api/content/${(_b = event.context.params) == null ? void 0 : _b.contentType}/aggregate`
    });
  }
});

export { aggregate_get as default };
//# sourceMappingURL=aggregate.get.mjs.map
