import { d as defineEventHandler, c as createError, r as requireAuth, cI as requireAdminScope, eN as getSchemaRevision, a as getSchemaManager, bs as SchemaValidationError, b as getDatabaseManager, ez as emitSchemaSync, eM as emitSchemaUpdate, eQ as emitSchemaCreate, eL as createSchemaRevision } from '../../../../../../nitro/nitro.mjs';
import { g as getAuditActorFromEvent } from '../../../../../../_/audit-log-actor.mjs';
import { i as invalidateGraphQLSchema } from '../../../../../../_/schema-builder.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 'graphql';

const restore_post = defineEventHandler(async (event) => {
  var _a, _b, _c, _d, _e;
  try {
    const name = (_a = event.context.params) == null ? void 0 : _a.name;
    const revisionId = (_b = event.context.params) == null ? void 0 : _b.revisionId;
    if (!name || !revisionId) {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: "Schema name and revision ID are required"
      });
    }
    await requireAuth(event);
    await requireAdminScope(event, "admin:schemas:write");
    const numericRevisionId = parseInt(revisionId);
    if (isNaN(numericRevisionId)) {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: "Revision ID must be a valid number"
      });
    }
    const revision = await getSchemaRevision(numericRevisionId);
    if (!revision) {
      throw createError({
        statusCode: 404,
        statusMessage: "Not Found",
        message: `Revision with id ${revisionId} not found`
      });
    }
    if (revision.schemaName !== name) {
      throw createError({
        statusCode: 404,
        statusMessage: "Not Found",
        message: `Revision does not belong to schema '${name}'`
      });
    }
    if (revision.action === "delete") {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: "Cannot restore a deletion revision. Use the previous revision to restore the schema."
      });
    }
    const manager = getSchemaManager();
    const restoredSchema = revision.data;
    if (((_c = restoredSchema == null ? void 0 : restoredSchema.info) == null ? void 0 : _c.singularName) !== name) {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: "Revision data is corrupted: singularName does not match"
      });
    }
    const existingSchema = manager.getSchema(name);
    try {
      manager.saveSchema(restoredSchema);
      invalidateGraphQLSchema();
    } catch (error) {
      if (error instanceof SchemaValidationError) {
        throw createError({
          statusCode: 400,
          statusMessage: "Validation Error",
          message: "Restored schema failed validation",
          data: error.result.errors
        });
      }
      throw error;
    }
    try {
      const dbManager = getDatabaseManager();
      await dbManager.syncSchemas();
      const schemaNames = manager.getAllSchemas().map((s) => s.info.singularName);
      await emitSchemaSync(schemaNames);
    } catch (syncError) {
      console.error(
        "[POST /api/schemas/:name/revisions/:revisionId/restore] Database sync error:",
        syncError
      );
    }
    const actor = getAuditActorFromEvent(event);
    if (existingSchema) {
      await emitSchemaUpdate(name, restoredSchema, existingSchema, actor);
    } else {
      await emitSchemaCreate(name, restoredSchema, actor);
    }
    try {
      await createSchemaRevision(
        name,
        "restore",
        restoredSchema,
        (_e = (_d = event.context.adminUser) == null ? void 0 : _d.id) != null ? _e : null
      );
    } catch (revisionError) {
      console.error(
        "[POST /api/schemas/:name/revisions/:revisionId/restore] Failed to record schema revision:",
        revisionError
      );
    }
    return {
      success: true,
      message: `Schema '${name}' restored to revision ${revision.revisionNumber}`,
      data: restoredSchema
    };
  } catch (error) {
    if (error && typeof error === "object" && "statusCode" in error) {
      throw error;
    }
    console.error("[POST /api/schemas/:name/revisions/:revisionId/restore] Error:", error);
    throw createError({
      statusCode: 500,
      statusMessage: "Failed to restore schema revision",
      message: error instanceof Error ? error.message : "Unknown error"
    });
  }
});

export { restore_post as default };
//# sourceMappingURL=restore.post.mjs.map
