import { db } from '../db/db_index'
import { keyValStore } from '../db/schema'
import { eq } from 'drizzle-orm'
import { castConstValue } from '../lib/const-keys'

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: castConstValue(c.key, c.value),
  }))
}

export async function upsertConstants(constants: Constant[]): Promise<void> {
  await db.transaction(async (tx) => {
    for (const { key, value } of constants) {
      const castedValue = castConstValue(key, value)
      const existing = await tx.query.keyValStore.findFirst({
        where: eq(keyValStore.key, key),
        columns: { key: true },
      })

      if (existing) {
        await tx.update(keyValStore)
          .set({ value: castedValue })
          .where(eq(keyValStore.key, key))
      } else {
        await tx.insert(keyValStore)
          .values({ key, value: castedValue })
      }
    }
  })
}
