/**
 * What every host/admin server action returns to its form (via useActionState). Kept serialisable
 * and minimal: never a raw database row.
 */
export type ActionResult =
  | { status: 'idle' }
  | {
      status: 'success';
      message: string;
      /** A one-time secret (temporary password) to show exactly once. */
      secret?: { label: string; value: string };
      /** A follow-up link shown with the message (e.g. "Open the new venue"). */
      link?: { href: string; label: string };
      /** Where the form should send the user next (client-side), if anywhere. */
      redirectTo?: string;
    }
  | { status: 'error'; message: string; fieldErrors?: Record<string, string> };

export const IDLE: ActionResult = { status: 'idle' };

export function actionError(message: string, fieldErrors?: Record<string, string>): ActionResult {
  return fieldErrors ? { status: 'error', message, fieldErrors } : { status: 'error', message };
}

export function actionOk(
  message: string,
  extra: { secret?: { label: string; value: string }; link?: { href: string; label: string }; redirectTo?: string } = {},
): ActionResult {
  return { status: 'success', message, ...extra };
}

/** Same copy everywhere for optimistic-concurrency conflicts. */
export const CONFLICT_MESSAGE = 'Someone else changed this while you were editing. Reload the page to see the latest version, then make your change again.';

export function fieldError(result: ActionResult, name: string): string | undefined {
  return result.status === 'error' ? result.fieldErrors?.[name] : undefined;
}
