'use server';

import { updateCustomer } from '@lib/data/customer';

import { AccountSubmitData, createAuthApi } from '@kit/auth/api';
import { enhanceAction } from '@kit/next/actions';
import { pathsConfig } from '@kit/shared/config';
import { getSupabaseServerClient } from '@kit/supabase/server-client';

import { UpdateAccountSchemaServer } from '../schemas/update-account.schema';

export const onUpdateAccount = enhanceAction(
  async (params: AccountSubmitData) => {
    const client = getSupabaseServerClient();
    const api = createAuthApi(client);

    try {
      await api.updateAccount(params);
    } catch (err: unknown) {
      if (err instanceof Error) {
        console.warn('On update account error: ' + err.message);
      }
      console.warn('On update account error: ', err);
    }

    try {
      await updateCustomer({
        first_name: params.firstName,
        last_name: params.lastName,
        phone: params.phone,
      });
    } catch (e) {
      console.error('Failed to update Medusa customer', e);
    }

    const hasUnseenMembershipConfirmation =
      await api.hasUnseenMembershipConfirmation();
    return {
      hasUnseenMembershipConfirmation,
    };
  },
  {
    schema: UpdateAccountSchemaServer,
  },
);
