import { db } from '../db/db_index';
import { keyValStore } from '../db/schema';

export interface Constant {
  key: string;
  value: any;
}

export async function getAllConstants(): Promise<Constant[]> {
  const constants = await db.select().from(keyValStore);

  return constants.map(c => ({
    key: c.key,
    value: c.value,
  }));
}

export async function upsertConstants(constants: Constant[]): Promise<void> {
  await db.transaction(async (tx) => {
    for (const { key, value } of constants) {
      await tx.insert(keyValStore)
        .values({ key, value })
        .onConflictDoUpdate({
          target: keyValStore.key,
          set: { value },
        });
    }
  });
}
