import { f as defineAdminEventHandler, h as requireAdminRole, O as requireMfaStepUp, q as readBody, c as createError, R as validateScopes, V as createApiToken } from '../../../nitro/nitro.mjs';
import { a as auditFromEvent } from '../../../_/audit-log-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 '../../../_/audit-log-actor.mjs';

const index_post = defineAdminEventHandler("admin:api-tokens:create", async (event) => {
  var _a, _b;
  try {
    await requireAdminRole(event, ["super-admin", "admin"]);
    await requireMfaStepUp(event);
    const body = await readBody(event);
    if (!body.name || typeof body.name !== "string" || body.name.trim().length === 0) {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: "Token name is required"
      });
    }
    if (body.name.trim().length > 255) {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: "Token name must be 255 characters or fewer"
      });
    }
    const scopeError = validateScopes(body.scopes);
    if (scopeError) {
      throw createError({
        statusCode: 400,
        statusMessage: "Bad Request",
        message: scopeError
      });
    }
    if (body.expiresAt) {
      const expiresDate = new Date(body.expiresAt);
      if (isNaN(expiresDate.getTime())) {
        throw createError({
          statusCode: 400,
          statusMessage: "Bad Request",
          message: "Invalid expiresAt date format"
        });
      }
      if (expiresDate <= /* @__PURE__ */ new Date()) {
        throw createError({
          statusCode: 400,
          statusMessage: "Bad Request",
          message: "expiresAt must be in the future"
        });
      }
    }
    if (body.serviceAccountId !== void 0 && body.serviceAccountId !== null) {
      if (!Number.isInteger(body.serviceAccountId) || body.serviceAccountId <= 0) {
        throw createError({
          statusCode: 400,
          statusMessage: "Bad Request",
          message: "serviceAccountId must be a positive integer or null"
        });
      }
    }
    const adminUser = event.context.adminUser;
    if (!adminUser) {
      throw createError({
        statusCode: 401,
        statusMessage: "Unauthorized",
        message: "Admin user required"
      });
    }
    const result = await createApiToken(adminUser.id, {
      name: body.name.trim(),
      description: (_a = body.description) == null ? void 0 : _a.trim(),
      scopes: body.scopes,
      expiresAt: body.expiresAt || null,
      serviceAccountId: (_b = body.serviceAccountId) != null ? _b : null
    });
    auditFromEvent(event, "api_token.create", {
      target: {
        entityType: "api_token",
        entityId: result.token.id,
        displayName: result.token.name
      },
      metadata: {
        scopes: result.token.scopes,
        expiresAt: result.token.expiresAt,
        serviceAccountId: result.token.serviceAccountId
      }
    });
    return {
      success: true,
      data: result.token,
      fullToken: result.fullToken
    };
  } catch (error) {
    if (error && typeof error === "object" && "statusCode" in error) {
      throw error;
    }
    const errorMessage = error instanceof Error ? error.message : "Unknown error";
    if (errorMessage === "Service account not found") {
      throw createError({
        statusCode: 404,
        statusMessage: "Not Found",
        message: errorMessage
      });
    }
    console.error("[POST /api/admin/api-tokens] Error:", error);
    throw createError({
      statusCode: 500,
      statusMessage: "Failed to create API token",
      message: errorMessage
    });
  }
});

export { index_post as default };
//# sourceMappingURL=index.post.mjs.map
