'use server';

import { redirect } from 'next/navigation';

import { enhanceAction } from '@kit/next/actions';
import { getSupabaseServerClient } from '@kit/supabase/server-client';

import pathsConfig from '~/config/paths.config';

import { UpdateAccountSchema } from '../../schemas/update-account.schema';
import { createAuthApi } from '../api';

export interface AccountSubmitData {
  firstName: string;
  lastName: string;
  personalCode: string;
  email: string;
  phone?: string;
  city?: string;
  weight: number | null;
  height: number | null;
  userConsent: boolean;
}

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

    try {
      await api.updateAccount(params);
      console.log('SUCCESS', pathsConfig.auth.updateAccountSuccess);
    } catch (err: unknown) {
      if (err instanceof Error) {
        console.warn('On update account error: ' + err.message);
      }
      console.warn('On update account error: ', err);
    }
    redirect(pathsConfig.auth.updateAccountSuccess);
  },
  {
    schema: UpdateAccountSchema,
  },
);
