import { createServerFn } from "@tanstack/react-start";
import { superTokensFunctionMiddleware } from "@/utils/supertokens";
import { serverFnLoggingMiddleware } from "@/utils/activities";

export const updateUserColorScheme = createServerFn({ method: "POST" })
  .validator((data: string) => data)
  .middleware([superTokensFunctionMiddleware, serverFnLoggingMiddleware])
  .handler(async ({ context, data }) => {
    const { userAuthId, metadata } = context;
    if (!userAuthId) return;

    const { updateUserMetadataFields } = await import(
      "@/utils/supertokens-core.server"
    );

    await updateUserMetadataFields(userAuthId, {
      colorScheme: data,
    });

    return {
      metadata: {
        ...metadata,
        colorScheme: data,
      },
    };
  });

export const updateUserLocale = createServerFn({ method: "POST" })
  .validator((data: string) => data)
  .middleware([superTokensFunctionMiddleware, serverFnLoggingMiddleware])
  .handler(async ({ context, data }) => {
    const { userAuthId, metadata } = context;
    if (!userAuthId) return;

    const { SUPPORTED_LOCALES } = await import("@/lib/i18n");
    if (!(SUPPORTED_LOCALES as readonly string[]).includes(data)) return;

    const { updateUserMetadataFields } = await import(
      "@/utils/supertokens-core.server"
    );

    await updateUserMetadataFields(userAuthId, {
      locale: data,
    });

    return {
      metadata: {
        ...metadata,
        locale: data,
      },
    };
  });

export const updateUserAccentColor = createServerFn({ method: "POST" })
  .validator((data: string) => data)
  .middleware([superTokensFunctionMiddleware, serverFnLoggingMiddleware])
  .handler(async ({ context, data }) => {
    const { userAuthId, metadata } = context;
    if (!userAuthId) return;

    const { updateUserMetadataFields } = await import(
      "@/utils/supertokens-core.server"
    );

    await updateUserMetadataFields(userAuthId, {
      accentColor: data,
    });

    return {
      metadata: {
        ...metadata,
        accentColor: data,
      },
    };
  });
