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

/**
 * Toggle flash delivery availability for specific products
 * @param isAvailable - Whether flash delivery should be available
 * @param productIds - Array of product IDs to update
 */
export async function toggleFlashDeliveryForItems(
  isAvailable: boolean,
  productIds: number[]
): Promise<void> {
  await db
    .update(productInfo)
    .set({ isFlashAvailable: isAvailable })
    .where(inArray(productInfo.id, productIds))
}

/**
 * Update key-value store
 * @param key - The key to update
 * @param value - The boolean value to set
 */
export async function toggleKeyVal(
  key: string,
  value: boolean
): Promise<void> {
  await db
    .update(keyValStore)
    .set({ value: value+'' })
    .where(eq(keyValStore.key, key))
}

/**
 * Get all key-value store constants
 * @returns Array of all key-value pairs
 */
export async function getAllKeyValStore(): Promise<Array<{ key: string; value: any }>> {
  const records = await db.select().from(keyValStore)
  return records.map((record) => ({
    key: record.key,
    value: castConstValue(record.key, record.value),
  }))
}
