import { router, protectedProcedure } from '@/src/trpc/trpc-index'
import { z } from 'zod';
import { computeConstants } from '@/src/lib/const-store'
import { CONST_KEYS } from '@/src/lib/const-keys'
import { getAllConstants as getAllConstantsFromDb, upsertConstants as upsertConstantsInDb } from '@/src/dbService'
import type { Constant, ConstantUpdateResult } from '@packages/shared'

export const constRouter = router({
  getConstants: protectedProcedure
    .query(async (): Promise<Constant[]> => {
      // Using dbService helper (new implementation)
      const constants = await getAllConstantsFromDb();

      /*
      // Old implementation - direct DB query:
      const constants = await db.select().from(keyValStore);

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

  updateConstants: protectedProcedure
    .input(z.object({
      constants: z.array(z.object({
        key: z.string(),
        value: z.any(),
      })),
    }))
    .mutation(async ({ input }): Promise<ConstantUpdateResult> => {
      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(', ')}`);
      }

      console.log(input)
      // Using dbService helper (new implementation)
      await upsertConstantsInDb(constants);

      /*
      // Old implementation - direct DB query:
      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),
      };
    }),
});
