"use strict";
const utils = require("./utils-3L7vCF_z.cjs");
const index = require("./index-QSf6WJj0.cjs");
const user = require("./user-d8lRSBlE.cjs");
const getEnabledAppsFromCredentials = async (credentials, options) => {
  const { where: _where = {}, filterOnCredentials = false } = options || {};
  const filterOnIds = {
    credentials: {
      some: {
        OR: []
      }
    }
  };
  const delegationCredentialsWithAppId = credentials.filter((credential) => user.isDelegationCredential({ credentialId: credential.id })).filter((credential) => credential.appId !== null);
  if (filterOnCredentials) {
    const userIds = [], teamIds = [];
    for (const credential of credentials) {
      if (credential.userId)
        userIds.push(credential.userId);
      if (credential.teamId)
        teamIds.push(credential.teamId);
    }
    if (userIds.length)
      filterOnIds.credentials.some.OR.push({ userId: { in: userIds } });
    if (teamIds.length)
      filterOnIds.credentials.some.OR.push({ teamId: { in: teamIds } });
  }
  const where = {
    enabled: true,
    ..._where,
    ...filterOnIds.credentials.some.OR.length && filterOnIds
  };
  let enabledApps = await index.prisma.app.findMany({
    where,
    select: { slug: true, enabled: true }
  });
  const delegationCredentialSupportedEnabledApps = await index.prisma.app.findMany({
    where: {
      enabled: true,
      slug: {
        in: delegationCredentialsWithAppId.map((credential) => credential.appId)
      }
    },
    select: { slug: true, enabled: true }
  });
  enabledApps = [...enabledApps, ...delegationCredentialSupportedEnabledApps];
  const apps = utils.getApps(credentials, filterOnCredentials);
  const filteredApps = apps.reduce((reducedArray, app) => {
    const appDbQuery = enabledApps.find((metadata) => metadata.slug === app.slug);
    if (appDbQuery?.enabled || app.isGlobal) {
      reducedArray.push({ ...app, enabled: true });
    }
    return reducedArray;
  }, []);
  return filteredApps;
};
exports.getEnabledAppsFromCredentials = getEnabledAppsFromCredentials;
