import { type ActionError, isInputError } from 'astro:actions';
import { popupState } from '@components/popup/Popup.ts';

export function actionErrorPopup<E extends Record<string, any>>(
  error: ActionError<E>,
  values?: { title?: string; message?: string }
) {
  let title = values?.title;
  if (title == undefined) {
    if (isInputError(error)) {
      title = 'Fehler (ungültige Eingabe)';
    } else {
      title = `Fehler (${error.status})`;
    }
  }

  let message = values?.message;
  if (message == undefined) {
    if (isInputError(error)) {
      const messages = [];
      for (const [name, msgs] of Object.entries(error.fields)) {
        messages.push(`${name}: ${(msgs as string[]).join(', ')}`);
      }
      message = messages.join('\n');
    } else {
      message = error.message;
    }
  }

  popupState.set({
    type: 'error',
    title: title,
    message: message
  });
}
