const API_URL = process.env.NEXT_PUBLIC_API_URL?.replace(/\/$/, '');

type RegistrationResponse = {
  message?: string | string[];
  [key: string]: unknown;
};

export async function createRegistration(
  data: Record<string, unknown>,
) {
  if (!API_URL) {
    throw new Error(
      'Registration service is not configured. Set NEXT_PUBLIC_API_URL to the backend URL.',
    );
  }

  const response = await fetch(
    `${API_URL}/api/v1/registrations`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(data),
    },
  );

  let result: RegistrationResponse | null = null;

  try {
    result = await response.json();
  } catch {
    result = null;
  }

  if (!response.ok) {
    const message =
      typeof result?.message === 'string'
        ? result.message
        : Array.isArray(result?.message)
          ? result.message.join(', ')
          : `Registration failed (${response.status})`;

    throw new Error(message);
  }

  return result;
}