class ApiKeyManager {
  /**
   * Genera una nueva API key con formato seguro
   * Formato: sk_live_1234567890abcdef... (56 caracteres total)
   */
  static async generateApiKey() {
    const environment = process.env.NODE_ENV === "production" ? "live" : "test";
    const randomBytes = new Uint8Array(32);
    crypto.getRandomValues(randomBytes);
    const randomHex = Array.from(randomBytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
    const prefix = `sk_${environment}_${randomHex.substring(0, 8)}`;
    const key = `${prefix}${randomHex.substring(8)}`;
    const encoder = new TextEncoder();
    const data = encoder.encode(key);
    const hashBuffer = await crypto.subtle.digest("SHA-256", data);
    const hashArray = new Uint8Array(hashBuffer);
    const hash = Array.from(hashArray, (byte) => byte.toString(16).padStart(2, "0")).join("");
    return { key, hash, prefix };
  }
  /**
   * Valida el formato de una API key
   */
  static validateKeyFormat(key) {
    const pattern = /^sk_(live|test)_[a-f0-9]{64}$/;
    return pattern.test(key);
  }
  /**
   * Extrae el prefix de una API key para identificación
   */
  static extractPrefix(key) {
    return key.substring(0, 16);
  }
  /**
   * Genera hash SHA-256 de una API key
   */
  static async hashKey(key) {
    const encoder = new TextEncoder();
    const data = encoder.encode(key);
    const hashBuffer = await crypto.subtle.digest("SHA-256", data);
    const hashArray = new Uint8Array(hashBuffer);
    return Array.from(hashArray, (byte) => byte.toString(16).padStart(2, "0")).join("");
  }
  /**
   * Valida que los scopes sean válidos
   */
  static validateScopes(scopes) {
    const validScopes = Object.keys(API_SCOPES);
    const invalidScopes = scopes.filter((scope) => !validScopes.includes(scope));
    return {
      valid: invalidScopes.length === 0,
      invalidScopes
    };
  }
  /**
   * Genera un nombre sugerido para la API key basado en scopes
   */
  static suggestKeyName(scopes) {
    if (scopes.includes("*")) {
      return "Full Access Key";
    }
    const categories = /* @__PURE__ */ new Set();
    scopes.forEach((scope) => {
      const [category] = scope.split(":");
      categories.add(category);
    });
    const categoryNames = Array.from(categories).join(", ");
    return `${categoryNames} Access Key`;
  }
}
const API_SCOPES = {
  // Usuarios
  "users:read": "Leer informaci\xF3n de usuarios",
  "users:write": "Crear y actualizar usuarios",
  "users:delete": "Eliminar usuarios",
  // Tasks
  "tasks:read": "Leer tasks",
  "tasks:write": "Crear y actualizar tasks",
  "tasks:delete": "Eliminar tasks",
  // Media (archivos, imágenes, videos)
  "media:read": "Leer informaci\xF3n de archivos y media",
  "media:write": "Subir y actualizar archivos",
  "media:delete": "Eliminar archivos",
  // Administración
  "admin:api-keys": "Gestionar API keys",
  "admin:users": "Administraci\xF3n completa de usuarios",
  // Comodín (solo para superadmins)
  "*": "Acceso completo (solo superadmin)"
};
const SCOPE_CATEGORIES = {
  users: {
    name: "Usuarios",
    description: "Gesti\xF3n de usuarios del sistema",
    scopes: ["users:read", "users:write", "users:delete"]
  },
  tasks: {
    name: "Tasks",
    description: "Gesti\xF3n de tareas y TODOs",
    scopes: ["tasks:read", "tasks:write", "tasks:delete"]
  },
  admin: {
    name: "Administraci\xF3n",
    description: "Funciones administrativas",
    scopes: ["admin:api-keys", "admin:users"]
  },
  system: {
    name: "Sistema",
    description: "Acceso completo al sistema",
    scopes: ["*"]
  }
};
const API_KEY_LIMITS = {
  maxKeysPerUser: parseInt(process.env.MAX_API_KEYS_PER_USER || "10"),
  maxKeyNameLength: 100,
  keyExpirationDays: 365
};
const RATE_LIMITS = {
  default: { requests: 1e3, windowMs: 6e4 },
  // 1000 req/min
  "users:write": { requests: 100, windowMs: 6e4 },
  // 100 req/min para escritura
  "users:delete": { requests: 10, windowMs: 6e4 },
  // 10 req/min para eliminación
  "tasks:write": { requests: 500, windowMs: 6e4 },
  // 500 req/min para tasks
  // Team invitation limits (prevent spam and abuse)
  "teams:invite": { requests: 20, windowMs: 6e4 },
  // 20 req/min - crear invitaciones
  "teams:invite:respond": { requests: 50, windowMs: 6e4 },
  // 50 req/min - aceptar/rechazar
  "*": { requests: 5e3, windowMs: 6e4 }
  // 5000 req/min para acceso completo
};
function getRateLimitForScopes(scopes) {
  if (scopes.includes("*")) {
    return RATE_LIMITS["*"];
  }
  let minRequests = RATE_LIMITS.default.requests;
  let windowMs = RATE_LIMITS.default.windowMs;
  for (const scope of scopes) {
    const limit = RATE_LIMITS[scope];
    if (limit && limit.requests < minRequests) {
      minRequests = limit.requests;
      windowMs = limit.windowMs;
    }
  }
  return { requests: minRequests, windowMs };
}
export {
  API_KEY_LIMITS,
  API_SCOPES,
  ApiKeyManager,
  RATE_LIMITS,
  SCOPE_CATEGORIES,
  getRateLimitForScopes
};
