"use server";

import { z } from "zod";
import { ZUserNotificationSettings } from "@formbricks/types/user";
import { getUser, updateUser } from "@/lib/user/service";
import { authenticatedActionClient } from "@/lib/utils/action-client";
import { withAuditLogging } from "@/modules/ee/audit-logs/lib/handler";

const ZUpdateNotificationSettingsAction = z.object({
  notificationSettings: ZUserNotificationSettings,
});

export const updateNotificationSettingsAction = authenticatedActionClient
  .inputSchema(ZUpdateNotificationSettingsAction)
  .action(
    withAuditLogging("updated", "user", async ({ ctx, parsedInput }) => {
      const oldObject = await getUser(ctx.user.id);
      const result = await updateUser(ctx.user.id, {
        notificationSettings: parsedInput.notificationSettings,
      });
      ctx.auditLoggingCtx.userId = ctx.user.id;
      ctx.auditLoggingCtx.oldObject = oldObject;
      ctx.auditLoggingCtx.newObject = result;
      return result;
    })
  );
