import { z } from 'zod';
import { router, withPermission } from '../trpc';

export const settingsRouter = router({
  list: withPermission('setting.read').query(async ({ ctx }) => {
    const rows = await ctx.prisma.setting.findMany({
      where: { organizationId: ctx.organizationId ?? undefined },
      orderBy: { key: 'asc' },
    });
    // value is JSON; stringify for a simple editable text field on the client.
    return rows.map((s) => ({ id: s.id, key: s.key, value: JSON.stringify(s.value) }));
  }),

  update: withPermission('setting.update')
    .input(z.object({ key: z.string(), value: z.string() }))
    .mutation(async ({ ctx, input }) => {
      // Store JSON when the text parses as JSON (number/bool/quoted string), else raw string.
      let value: unknown;
      try {
        value = JSON.parse(input.value);
      } catch {
        value = input.value;
      }
      await ctx.prisma.setting.upsert({
        where: { organizationId_key: { organizationId: ctx.organizationId ?? '', key: input.key } },
        update: { value: value as never },
        create: { organizationId: ctx.organizationId ?? '', key: input.key, value: value as never },
      });
      return { ok: true };
    }),
});
