'use server';

import z from 'zod';

import { enhanceAction } from '@kit/next/actions';
import { getLogger } from '@kit/shared/logger';

import {
  updatePersonalAccount,
  updatePersonalAccountPreferences,
} from '~/lib/services/account.service';

import {
  AccountPreferences,
  accountPreferencesSchema,
} from '../account-preferences.schema';
import {
  AccountSettings,
  accountSettingsSchema,
} from '../account-settings.schema';

export const updatePersonalAccountAction = enhanceAction(
  async ({ accountId, data }: { accountId: string; data: AccountSettings }) => {
    const logger = await getLogger();

    try {
      logger.info({ accountId }, 'Updating account');
      await updatePersonalAccount(accountId, data);
      logger.info({ accountId }, 'Successfully updated account');
      return { success: true };
    } catch (e) {
      logger.error('Failed to update account', JSON.stringify(e));

      return { success: false };
    }
  },
  {
    schema: z.object({ accountId: z.uuid(), data: accountSettingsSchema }),
  },
);

export const updatePersonalAccountPreferencesAction = enhanceAction(
  async ({
    accountId,
    data,
  }: {
    accountId: string;
    data: AccountPreferences;
  }) => {
    const logger = await getLogger();

    try {
      logger.info({ accountId }, 'Updating account preferences');
      await updatePersonalAccountPreferences(accountId, data);
      logger.info({ accountId }, 'Successfully updated account preferences');
      return { success: true };
    } catch (e) {
      logger.error('Failed to update account preferences', JSON.stringify(e));

      return { success: false };
    }
  },
  {
    schema: z.object({ accountId: z.uuid(), data: accountPreferencesSchema }),
  },
);
