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

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: c.value,
  }));
}

export async function upsertConstants(constants: Constant[]): Promise<void> {
  await db.transaction(async (tx) => {
    for (const { key, value } of constants) {
      await tx.insert(keyValStore)
        .values({ key, value })
        .onConflictDoUpdate({
          target: keyValStore.key,
          set: { value },
        });
    }
  });
}

const CACHE_VERSION_KEY = 'cache_version';

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;

    await tx.insert(keyValStore)
      .values({ key: CACHE_VERSION_KEY, value: nextValue })
      .onConflictDoUpdate({
        target: keyValStore.key,
        set: { value: nextValue },
      });

    return nextValue;
  });
}
