import { useDB, eq } from '../../utils/database'
import { siteconfig } from '../schema'

export async function getSiteConfig(key: string) {
  const db = useDB()
  const result = await db.select().from(siteconfig).where(eq(siteconfig.key, key)).limit(1)
  return result[0] || null
}

export async function getAllSiteConfigs() {
  const db = useDB()
  return db.select().from(siteconfig)
}

export async function setSiteConfig(key: string, value: string, description?: string) {
  const db = useDB()
  const existing = await getSiteConfig(key)

  if (existing) {
    return db
      .update(siteconfig)
      .set({ value, description, updatedAt: new Date() })
      .where(eq(siteconfig.key, key))
      .returning()
  } else {
    return db
      .insert(siteconfig)
      .values({ key, value, description })
      .returning()
  }
}

export async function deleteSiteConfig(key: string) {
  const db = useDB()
  return db.delete(siteconfig).where(eq(siteconfig.key, key)).returning()
}
