'use server';
import { safeFetchApi } from '@/lib/fetch.api';
import { createUserValue, UsersMutate } from '../schemas/register';

export const registerUserAction = async (payload: createUserValue) => {
  const { confirmPassword, ...payloadWithoutId } = payload;

  const [error, data] = await safeFetchApi(
    UsersMutate,
    '/auth/sing-up',
    'POST',
    payloadWithoutId,
  );

  if (error) {
    // console.error(error);
    if (error.message === 'Username already exists') {
      throw new Error('Ese usuario ya existe');
    }
    if (error.message === 'Email already exists') {
      throw new Error('Ese correo ya está en uso');
    }
    throw new Error('Error al crear el usuario');
  }

  return payloadWithoutId;
};