import { db } from '../db/db_index'
import { keyValStore } from '../db/schema'
import { eq } from 'drizzle-orm'
import { CONST_KEYS, 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 castedValue = 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 })
      }
    }
  })
}

const CACHE_VERSION_KEY = CONST_KEYS.cacheVersion

const parseCacheVersion = (value: unknown) => {
  const parsed = Number(value)
  return Number.isFinite(parsed) ? parsed : 0
}

export async function getCacheVersion(): Promise<number> {
  const record = await db.query.keyValStore.findFirst({
    where: eq(keyValStore.key, CACHE_VERSION_KEY),
    columns: { value: true },
  })

  return record ? parseCacheVersion(record.value) : 0
}

export async function incrementCacheVersion(): Promise<number> {
  return db.transaction(async (tx) => {
    const existing = await tx.query.keyValStore.findFirst({
      where: eq(keyValStore.key, CACHE_VERSION_KEY),
      columns: { value: true },
    })

    const nextValue = parseCacheVersion(existing?.value) + 1

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

    return nextValue
  })
}
