import { eq } from 'drizzle-orm';
import { db } from '../db';
import { serverConfig } from './schema';

const SETTINGS_KEY = 'server-settings';

export async function readServerSettings(): Promise<Record<string, unknown>> {
  const [row] = await db.select().from(serverConfig).where(eq(serverConfig.key, SETTINGS_KEY));
  return (row?.value as Record<string, unknown>) ?? {};
}

export async function writeServerSettings(settings: Record<string, unknown>): Promise<void> {
  await db
    .insert(serverConfig)
    .values({ key: SETTINGS_KEY, value: settings, updatedAt: new Date() })
    .onConflictDoUpdate({
      target: serverConfig.key,
      set: { value: settings, updatedAt: new Date() },
    });
}

export async function readConfigValue<T>(key: string, fallback: T): Promise<T> {
  const [row] = await db.select().from(serverConfig).where(eq(serverConfig.key, key));
  return (row?.value as T) ?? fallback;
}

export async function writeConfigValue(key: string, value: unknown): Promise<void> {
  await db
    .insert(serverConfig)
    .values({ key, value, updatedAt: new Date() })
    .onConflictDoUpdate({
      target: serverConfig.key,
      set: { value, updatedAt: new Date() },
    });
}
