import flatten from "lodash/flatten";
import { listActiveSchemas } from "./listActiveSchemas";
import { shardNo } from "./names";
import { promiseAllMap } from "./promiseAllMap";

export interface DiscoveredShard {
  dsn: string;
  shard: number;
  schema: string;
}

/**
 * Loads the list of all active schemas from the given DSNs.
 */
export async function discoverShards({
  dsns,
}: {
  dsns: string[];
}): Promise<DiscoveredShard[]> {
  return flatten(
    await promiseAllMap(dsns, async (dsn) =>
      (await listActiveSchemas({ dsn }))
        .filter((schema) => shardNo(schema) !== null)
        .map((schema) => ({ dsn, shard: shardNo(schema)!, schema })),
    ),
  );
}
