import { z } from "zod";
import { cachified, presenceCache } from "./cache.server.js";
import { getPreferences } from "./db.server.js";
import {
  PresenceSchema,
  UserSchema,
  partykitBaseUrl
} from "./presence.js";
async function getPresentUsers(user, { timings, request } = {}) {
  return cachified({
    key: "presence",
    cache: presenceCache,
    timings,
    request,
    ttl: 1e3 * 60 * 5,
    swr: 1e3 * 60 * 60 * 24,
    checkValue: z.array(UserSchema),
    async getFreshValue(context) {
      try {
        const response = await fetch(`${partykitBaseUrl}/presence`);
        if (!response.ok) {
          throw new Error(
            `Unexpected response from partykit: ${response.status} ${response.statusText}`
          );
        }
        const presence = PresenceSchema.parse(await response.json());
        const preferences = await getPreferences();
        const users = presence.users;
        if (preferences?.presence.optOut || !user) {
          return uniqueUsers(users.filter((u) => u.id !== user?.id));
        } else {
          return uniqueUsers([...users, user]);
        }
      } catch (err) {
        console.error(err);
        context.metadata.ttl = 300;
        return [];
      }
    }
  });
}
function uniqueUsers(users) {
  const seen = /* @__PURE__ */ new Set();
  return users.filter((user) => {
    if (seen.has(user.id)) {
      return false;
    }
    seen.add(user.id);
    return true;
  });
}
export {
  getPresentUsers
};
