import { router, protectedProcedure } from '../trpc-index';
import { z } from 'zod';
import { db } from '../../db/db_index';
import { keyValStore } from '../../db/schema';
import { computeConstants } from '../../lib/const-store';
import { CONST_KEYS } from '../../lib/const-keys';

export const constRouter = router({
  getConstants: protectedProcedure
    .query(async () => {
      
      const constants = await db.select().from(keyValStore);

      const resp = constants.map(c => ({
        key: c.key,
        value: c.value,
      }));
      
      return resp;
    }),

  updateConstants: protectedProcedure
    .input(z.object({
      constants: z.array(z.object({
        key: z.string(),
        value: z.any(),
      })),
    }))
    .mutation(async ({ input }) => {
      const { constants } = input;

      const validKeys = Object.values(CONST_KEYS) as string[];
      const invalidKeys = constants
        .filter(c => !validKeys.includes(c.key))
        .map(c => c.key);

      if (invalidKeys.length > 0) {
        throw new Error(`Invalid constant keys: ${invalidKeys.join(', ')}`);
      }

      await db.transaction(async (tx) => {
        for (const { key, value } of constants) {
          await tx.insert(keyValStore)
            .values({ key, value })
            .onConflictDoUpdate({
              target: keyValStore.key,
              set: { value },
            });
        }
      });

      // Refresh all constants in Redis after database update
      await computeConstants();

      return {
        success: true,
        updatedCount: constants.length,
        keys: constants.map(c => c.key),
      };
    }),
});