import "server-only";
import { cache } from "react";
import { api } from "../../convex/_generated/api";
import { q, token } from "./convex-server";
import { DEFAULT_SETTINGS, type AppSettings } from "./settings-defaults";

export { DEFAULT_SETTINGS };
export type { AppSettings };

/**
 * Business settings live in Convex. Signed-in staff get the full document;
 * the public login shell only receives the presentation subset.
 */
export const getSettings = cache(async (): Promise<AppSettings> => {
  try {
    const t = await token();
    if (t) return { ...DEFAULT_SETTINGS, ...((await q(api.settings.get, {})) as Partial<AppSettings>) };
    const pub = await q(api.settings.publicInfo, {});
    return { ...DEFAULT_SETTINGS, ...pub };
  } catch {
    return DEFAULT_SETTINGS;
  }
});
