// Extract a human-readable message from any error shape

/**
 * Normalize any caught error value into a readable string.
 * Handles: string, Error, Tauri IPC errors, Rust AppError {kind, detail}, objects with .message.
 */
export function extractErrorMessage(err: unknown): string {
  if (typeof err === 'string') return err;
  if (err instanceof Error) return err.message;
  if (err && typeof err === 'object') {
    const obj = err as Record<string, unknown>;
    // Rust AppError tagged enum: { kind: "Database", detail: { ... } }
    if ('kind' in obj && typeof obj.kind === 'string') {
      if ('detail' in obj && obj.detail) {
        const detail = typeof obj.detail === 'string'
          ? obj.detail
          : JSON.stringify(obj.detail);
        return `${obj.kind}: ${detail}`;
      }
      return obj.kind;
    }
    // Generic object with message property
    if ('message' in obj && typeof obj.message === 'string') return obj.message;
  }
  return String(err);
}
