import type { MutationCtx, QueryCtx } from "../_generated/server";
import { DEFAULT_SETTINGS, type AppSettings } from "../../src/lib/settings-defaults";

export type { AppSettings };

/** Merge stored overrides over the defaults. Cheap: the table holds a few dozen rows. */
export async function getSettings(ctx: QueryCtx | MutationCtx): Promise<AppSettings> {
  const rows = await ctx.db.query("settings").collect();
  const merged: Record<string, unknown> = { ...DEFAULT_SETTINGS };
  for (const r of rows) merged[r.key] = r.value;
  return merged as unknown as AppSettings;
}

export async function saveSettings(ctx: MutationCtx, patch: Partial<AppSettings>, group = "general") {
  for (const [key, value] of Object.entries(patch)) {
    const row = await ctx.db.query("settings").withIndex("by_key", (q) => q.eq("key", key)).unique();
    if (row) await ctx.db.patch(row._id, { value, group, updatedAt: Date.now() });
    else await ctx.db.insert("settings", { key, value, group, updatedAt: Date.now() });
  }
}
