import { f as defineAdminEventHandler, h as requireAdminRole, q as readBody, c as createError, a as getSchemaManager, z as withAIGuardrails, B as approxBodyBytes, G as createContentManager, H as ComponentRegistry, I as analyzeEditorialContent, E as dbQuery, b as getDatabaseManager } from '../../../../nitro/nitro.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';

function toNullableString(value) {
  return typeof value === "string" ? value : null;
}
function toNullableNumber(value) {
  return typeof value === "number" && Number.isFinite(value) ? value : null;
}
function tableNameOf(pluralName) {
  return pluralName.toLowerCase().replace(/-/g, "_");
}
function quoteIdent(name) {
  if (!/^[a-z_][a-z0-9_]*$/i.test(name)) {
    throw new Error(`Unsafe identifier: ${name}`);
  }
  const dialect = getDatabaseManager().getDialect();
  return dialect === "mysql" ? `\`${name}\`` : `"${name}"`;
}
const editorialQa_post = defineAdminEventHandler("admin:ai:editorial-qa", async (event) => {
  var _a;
  await requireAdminRole(event, ["super-admin", "admin", "editor"]);
  const body = (_a = await readBody(event)) != null ? _a : {};
  const schemaName = typeof body.schemaName === "string" ? body.schemaName : "";
  if (!schemaName) {
    throw createError({
      statusCode: 400,
      statusMessage: "Bad Request",
      message: 'Body must include "schemaName" (singularName of the content schema).'
    });
  }
  const schemaManager = getSchemaManager();
  const schema = schemaManager.getSchema(schemaName);
  if (!schema) {
    throw createError({
      statusCode: 404,
      statusMessage: "Schema Not Found",
      message: `Schema "${schemaName}" is not registered.`
    });
  }
  const intentToPublish = body.intentToPublish === true;
  const data = await withAIGuardrails({
    advisor: "editorial-qa",
    event,
    bodyBytes: approxBodyBytes(body),
    inputDigest: {
      schemaName,
      intentToPublish,
      contentId: typeof body.contentId === "number" ? body.contentId : null
    },
    run: async () => {
      let content;
      if (body.content && typeof body.content === "object" && !Array.isArray(body.content)) {
        content = body.content;
      } else if (typeof body.contentId === "number" && Number.isInteger(body.contentId)) {
        const manager = createContentManager(schemaName);
        const record = await manager.findOne(body.contentId);
        if (!record) {
          throw createError({
            statusCode: 404,
            statusMessage: "Content Not Found",
            message: `Record ${body.contentId} of schema "${schemaName}" not found or not visible.`
          });
        }
        content = record;
      } else {
        throw createError({
          statusCode: 400,
          statusMessage: "Bad Request",
          message: 'Body must include either "content" object or "contentId" number.'
        });
      }
      const allSchemas = schemaManager.getAllSchemas();
      const schemaByName = new Map(allSchemas.map((s) => [s.info.singularName, s]));
      const context = {
        components: ComponentRegistry.getAll(),
        mediaResolver: async (ids) => {
          const map = /* @__PURE__ */ new Map();
          if (ids.length === 0 || !schemaByName.has("media")) {
            return map;
          }
          const mediaManager = createContentManager("media");
          for (const id of ids) {
            const record = await mediaManager.findOne(id).catch(() => null);
            if (!record) {
              continue;
            }
            map.set(id, {
              id,
              alt: toNullableString(record.alt),
              caption: toNullableString(record.caption),
              mime: toNullableString(record.mimeType),
              size: toNullableNumber(record.size),
              width: toNullableNumber(record.width),
              height: toNullableNumber(record.height),
              name: toNullableString(record.filename)
            });
          }
          return map;
        },
        referenceResolver: async (target, ids) => {
          var _a2;
          const targetSchema = schemaByName.get(target);
          if (!targetSchema || ids.length === 0) {
            return /* @__PURE__ */ new Map();
          }
          const tableName = tableNameOf(targetSchema.info.pluralName);
          let quotedTableName;
          try {
            quotedTableName = quoteIdent(tableName);
          } catch {
            return /* @__PURE__ */ new Map();
          }
          const placeholders = ids.map(() => "?").join(", ");
          const supportsPublishing = ((_a2 = targetSchema.options) == null ? void 0 : _a2.draftAndPublish) === true;
          const sql = supportsPublishing ? `SELECT id, published_at FROM ${quotedTableName} WHERE id IN (${placeholders})` : `SELECT id FROM ${quotedTableName} WHERE id IN (${placeholders})`;
          let rows = [];
          try {
            rows = await dbQuery(sql, ids);
          } catch {
            return /* @__PURE__ */ new Map();
          }
          const map = /* @__PURE__ */ new Map();
          for (const id of ids) {
            const row = rows.find((r) => r.id === id);
            if (!row) {
              map.set(id, { id, exists: false });
            } else {
              map.set(id, {
                id,
                exists: true,
                published: supportsPublishing ? row.published_at !== null : void 0
              });
            }
          }
          return map;
        }
      };
      const request = {
        intentToPublish
      };
      return analyzeEditorialContent(request, schema, content, context);
    },
    digestOutput: (result) => ({
      suggestions: result.findings.length,
      bySeverity: result.findings.reduce((acc, f) => {
        var _a2;
        acc[f.severity] = ((_a2 = acc[f.severity]) != null ? _a2 : 0) + 1;
        return acc;
      }, {})
    })
  });
  return { success: true, data };
});

export { editorialQa_post as default };
//# sourceMappingURL=editorial-qa.post.mjs.map
